2011-08-26 25 views
5

を使用して、ネストされた要素を反復処理:jQueryの:私はこの基本的なHTML構造を持っている各

<div class=a> 
    <div class=m></div> 
    <div class=m></div> 
</div> 
<div class=b> 
    <div class=m></div> 
    <div class=m></div> 
</div> 

は今、私はすべてのmのを反復処理したいが、また、私がまたはbにいるかどうかを知りたいと思います。 基本的なjquery構文を使用して、これを見つけ出すことができません。

$('.m').each(function(index) { 
    // how do i know if this m is part of a or b ? 
}); 

答えて

8

$(this).parent().hasClass("a")または$(this).parent().hasClass("b")

0
$('.m').each(function(index) { 
    this.parentNode.getAttribute("class"); 
}); 
0

例えば、親が.a

if($(this).parent().is('.a')) 
1
if($(this).parent().hasClass('a')) 

とBについても同様である、それが動作するはずです確認してください。あなたが気にした場合

var $this = $(this); 
if ($this.closest("a").length === 1) { 
    alert("I'm in an a div"); 
} 
else { 
    alert("I'm in a b div"); 
} 
0

あなたは.closestメソッドを使用することができますあなたが「A」または「B」である場合、あなたの関数を識別するために

$('.m').each(function() { 
    var parentClass = $(this).parent().attr('class'); 
}); 

ので、parentClassのVaRはeitheの値を持つ必要がありますr 'a'または 'b'

1

が、その後、私はこのようなセレクタを分離したい::

$('.a .m').each(function(index) { 
    // now I'm on .a items 
}); 

$('.b .m').each(function(index) { 
    // now I'm on .b items 
}); 
0

あなたが内部の親要素のクラスを確認することができます

関連する問題