简体   繁体   English

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

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

I realize the code below is not the most efficient way of grabbing elements, but for the sake of an example... 我意识到下面的代码并不是抓取元素的最有效方法,但是为了一个例子......

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

Something like this, 像这样的东西,

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

No need to store variables. 无需存储变量。 jQuery already does this in the second parameter... 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
  });
});

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

That should work. 这应该工作。

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

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