关注javascript
具有getAjax
功能。这是在html表单中调用每个鼠标选择事件。我必须在每个事件中调用相同的函数。当我想修改getAjax
函数时,必须为所有事件做。有没有办法让getAjax
函数保持一个位置并在每个鼠标事件中调用。
注意:所有选择元素都在同一个容器中
<script type = "text/javascript" >
$(document).ready(function() {
var age1 = 21;
var age2 = 35;
var salary = 10000;
var width = 410;
var height = 510;
getAjax(ajaxUrl, salary, age1, age2, width, height);
$("#age1").change(function() {
age1 = parseInt($(this).val());
getAjax(ajaxUrl, salary, age1, age2, width, height);
});
$("#age2").change(function() {
age2 = parseInt($(this).val());
getAjax(ajaxUrl, salary, age1, age2, width, height);
});
$("#salary").change(function() {
salary = parseInt($(this).val());
getAjax(ajaxUrl, salary, age1, age2, width, height);
});
$("#width").change(function() {
width = parseInt($(this).val());
getAjax(ajaxUrl, salary, age1, age2, width, height);
});
$("#height").change(function() {
height = parseInt($(this).val());
getAjax(ajaxUrl, salary, age1, age2, width, height);
});
});
function getAjax(URL, salary, age1, age2, width, height) {
$.ajax({
url: URL,
data: {
sala: salary,
age1: age1,
age2: age2,
het1: width,
het2: height
},
dataType: "html",
type: "POST",
success: function(retdata) {
$("#data1").html(retdata);
}
});
} </script>
答案 0 :(得分:5)
你可以组合选择器,你可以重写变量,也可以重写一个对象,这样可以使一切变得更紧凑。
$(function() {
var data = {
age1 : 21,
age2 : 35,
salary : 10000,
width : 410,
height : 510
};
getAjax(ajaxUrl, data.salary, data.age1, data.age2, data.width, data.height);
$("#age1, #age2, #salary, #width, #height").change(function() {
data[$(this).attr("id")] = parseInt($(this).val());
getAjax(ajaxUrl, data.salary, data.age1, data.age2, data.width, data.height);
});
});
如果您更改getAjax
函数以使用该对象,情况会更好。这将为您节省更多代码。
$(function() {
var data = {
age1 : 21,
age2 : 35,
salary : 10000,
width : 410,
height : 510
};
getAjax(ajaxUrl, data);
$("#age1, #age2, #salary, #width, #height").change(function() {
data[$(this).attr("id")] = parseInt($(this).val());
getAjax(ajaxUrl, data);
});
});
function getAjax(URL, data) {
$.ajax({
url: URL,
data: data,
dataType: "html",
type: "POST",
success: function(retdata) {
$("#data1").html(retdata);
}
});
}
答案 1 :(得分:1)
低效,但无关紧要,但代码中只有一个事件监听器。
<script type = "text/javascript" >
$(document).ready(function() {
var age1 = 21;
var age2 = 35;
var salary = 10000;
var width = 410;
var height = 510;
getAjax(ajaxUrl, salary, age1, age2, width, height);
$("#age1,#age2,#salary,#width,#height").change(function() {
age1 = parseInt($('#age1').val());
age2 = parseInt($('#age2').val());
salary = parseInt($('#salary').val());
width = parseInt($('#width').val());
height = parseInt($('#height').val());
getAjax(ajaxUrl, salary, age1, age2, width, height);
});
});
function getAjax(URL, salary, age1, age2, width, height) {
$.ajax({
url: URL,
data: {
sala: salary,
age1: age1,
age2: age2,
het1: width,
het2: height
},
dataType: "html",
type: "POST",
success: function(retdata) {
$("#data1").html(retdata);
}
});
} </script>