$.每个带有Ajax和变量修改

$.each with Ajax and Variable Modification

本文关键字:变量 修改 Ajax      更新时间:2023-09-26

为什么whereString返回"where"而不是"where"+一些数据。我知道这与闭包和作用域有关,但我不确定如何解决它

感谢您提前提供的帮助。

这是代码:

    function SomeFunction() {
        var whereString = "where ";
        var seperator = " ";
        $.when.apply($(".SomeClass").each(function () {
             var promise = SomeAjaxCall().done(function (data) {
                whereString += seperator + data.d
             });
             seperator = "and "
       }).then(function() { 
         alert("Finished");
         alert(whereString); // Alerts "where " and not "Where "+data.d
      })
   };

注意,.apply()希望this上下文设置为第一个参数,数组设置为第二个参数;.each()不返回数组,而且.each()在Question的js处似乎缺少右括号)

尝试将.map()替换为.each(),并将.get()链接到.map()以返回jQuery promise对象的数组,将$.when.applycontext:this设置为$。此外,在.map()中包含return promise,以将jQuery promise对象返回给.then()

function SomeFunction() {
  var whereString = "where ";
  var seperator = " ";
  // set `this` to `jQuery` alias `$`
  $.when.apply($, $(".SomeClass").map(function(i, el) {
    // do ajax stuff
    var promise = SomeAjaxCall().done(function (data) {
                    whereString += seperator + data.d
                  });
    seperator = "and ";
    // return jQuery promise object
    return promise
  // include closing parenthesis to `.map()` , use `.get()` to return
  // array of jQuery promise objects
  }).get()).then(function() {
    alert("Finished");
    alert(whereString); 
  })
};

function SomeFunction() {
  var whereString = "where";
  var seperator = " ";
  // set `this` to `jQuery` alias `$`
  $.when.apply($, $(".SomeClass").map(function(i, el) {
    // do asynchronous stuff
    var promise = $.Deferred().resolve({
      "d": el.textContent
    }).done(function(data) {
      whereString += seperator + data.d
    });
    seperator = " and ";
    // return jQuery promise
    return promise
  // include closing parenthesis to `.map()` , use `.get()` to return
  // array of jQuery promise objects
  }).get()).then(function() {
    console.log("Finished");
    console.log(whereString); 
  })
};
SomeFunction()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div class="SomeClass">abc</div>
<div class="SomeClass">def</div>

这是因为在对jquery select的所有结果调用"each"函数后,警报就会触发。然而,SomeAjaxCall()是异步的,因此,"done"函数还没有被调用,因为在"each"函数执行完毕时,ajax调用还没有完成,因此会触发警报。

虽然这最终可能不是你想要的,但你可以在发出警报之前添加几秒钟的超时,以查看"位置"最终是否会更新。