2009-07-30 16 views
2

私は以下のコードは、各内側の前Varの要素をつかむの最も効率的な方法ではありませんが、例のために...jqueryで「THIS」のさまざまなレベルにアクセスするにはどうすればよいですか?

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

答えて

4

変数を格納する必要はありません。 jQueryのは、すでに... 2番目のパラメータで動作するはず

$(".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 
    }); 
}); 
+0

ええ、個人的に私はどこでもparamsが好きではありません。 var imoを使用するときれいになります。 – redsquare

3

店この実現。

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

'var firstClassThis = this;'は冗長です。 jQueryはすでにこれらの識別子を管理しています。私の答えを見てください。 – Sampson

+2

既にインデックスを使用している場合は、コードが見栄えがよくなります。インデックスを気にしなかった場合、おそらくローカル変数で 'this'をキャプチャします。 – SolutionYogi

+0

真。 +1 – Sampson

1
$('.myFirstClass').each(function(i){ 
    var me = this; 
    $(this).find('.mySecondClass').each(function(j){ 
     alert($(me).attr('id')); 
    }); 
}); 

をこれを行います。

+1

'me'変数に 'var'キーワードを指定する必要があります。 – SolutionYogi

関連する問題