【问题标题】:How do I access different levels of "THIS" in jquery?如何在 jquery 中访问不同级别的“THIS”?
【发布时间】:2009-07-30 16:44:52
【问题描述】:

我意识到下面的代码不是抓取元素的最有效方式,但为了举例......

$('.myFirstClass').each(function(i){
   // Here is the first 'THIS' occurrence
   $(this).find('.mySecondClass').each(function(j){
      // Here is the second 'THIS' occurrence
      // How do i access the first occurrence from here?
   });
});

【问题讨论】:

    标签: javascript jquery oop


    【解决方案1】:

    无需存储变量。 jQuery 已经在第二个参数中这样做了...

    $(".myFirstClass").each(function(i, j){
      // I am represented as this or j
      $(j).find(".mySecondClass").each(function(a, b){
        // I am represented as this or b
        // I can communicate with j
      });
    });
    

    【讨论】:

    • 是的,我个人不喜欢无处不在的参数。使用 var imo 更清洁。
    【解决方案2】:

    类似的,

    $('.myFirstClass').each(function(i){
       var firstClassThis = this;
       $(this).find('.mySecondClass').each(function(j){
          // Here is the second 'THIS' occurrence
          // How do i access the first occurrence from here?
          //You can use firstClassThis here due to closure. 
       });
    });
    

    【讨论】:

    • var firstClassThis = this; 是多余的。 jQuery 已经管理了这些标识符。看我的回答。
    • 如果您已经在使用索引,您的代码看起来会更好。如果我不关心索引,我可能会在局部变量中捕获“this”。
    • 是的。 +1
    【解决方案3】:

    将 this 存储在内部 each 之前的 var 中。

    $('.myFirstClass').each(function(i){
       //store this
       var $that = $(this);
       $(this).find('.mySecondClass').each(function(j){
          //$that.something
          // How do i access the first occurrence from here?
       });
    });
    

    【讨论】:

      【解决方案4】:
      $('.myFirstClass').each(function(i){
         var me = this;
         $(this).find('.mySecondClass').each(function(j){
            alert($(me).attr('id'));
         });
      });
      

      应该可以的。

      【讨论】:

      • 你应该为'me'变量指定'var'关键字。
      猜你喜欢
      • 1970-01-01
      • 2010-11-13
      • 2019-09-26
      • 2015-08-16
      • 2016-07-15
      • 2017-07-22
      • 1970-01-01
      • 2011-04-25
      • 1970-01-01
      相关资源
      最近更新 更多