[英]in javascript for loop is executing before the get method executes
In the following example variable e
contains all the selected clients from a select box, I am iterating them one by one in a for
loop and passing them via jQuery's get method to take values according to client but the for
loop is executing before get method ends and due to that it changes the value of val (which is next value). 在下面的示例中,变量
e
包含选择框中的所有选定客户端,我在for
循环中逐个迭代它们并通过jQuery的get方法传递它们以根据客户端获取值,但for
循环在get方法结束之前执行并且由于它改变了val的值(这是下一个值)。 How to resolve this problem ? 如何解决这个问题?
var e = document.getElementById("client");
for (var i = 0; i < e.options.length; i++) {
if (e.options[i].selected) {
var val = e.options[i].value;
alert(val); // here it is coming normally
$('#fund').append('<option value=' + select.options.length + '>---' + val + '----</option>');
$.get("listFundsForClient", { client: val }, function(data) {
alert("2nd:" + val);// here it is taking next value due to for loop iteration
});
}
}
it is because here val
is a closure variable, it can be re-written as 这是因为这里的
val
是一个闭包变量,它可以重写为
$('#client option:selected').each(function(){
var $this = $(this), val =$this.val();
alert(val); // here it is coming normally
$('#fund').append('<option value='+select.options.length+'>---'+val+'----</option>');
$.get("listFundsForClient", {client: val}, function(data) {
alert("2nd:"+val);// here it is taking next value due to for loop iteration
});
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.