0

我的代码看起来像

  $(".div-text").click(function(e) {
    e.preventDefault();
    $(this).parents(".items").find("img.mainImage").each(function() {
       // following this should correspond to mainImage elements and not outside "this"
       alert($(this).data("src")) ----------> **this "this" does not work**
    })
  });

我怎样才能有两个 this 对应于不同的元素或

上面代码的替代方法是什么???

4

1 回答 1

1

this循环内部是eachmainImage循环通过的电流,而不是单击的div-text元素。

一种可能的解决方案是使用闭包变量,如下所示

$(".div-text").click(function (e) {
    e.preventDefault();
    var self = this;
    $(this).parents(".items").find("img.mainImage").each(function () {
        // following this should correspond to mainImage elements and not outside "this"
        alert($(self).data("src"))
    })
});
于 2013-09-21T08:49:56.257 回答