繁体   English   中英

如何在jquery中访问不同级别的“THIS”?

[英]How do I access different levels of “THIS” in jquery?

我意识到下面的代码并不是抓取元素的最有效方法,但是为了一个例子......

$('.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?
   });
});

像这样的东西,

$('.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. 
   });
});

无需存储变量。 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之前。

$('.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?
   });
});
$('.myFirstClass').each(function(i){
   var me = this;
   $(this).find('.mySecondClass').each(function(j){
      alert($(me).attr('id'));
   });
});

这应该工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM