2011-08-26 38 views
5

我有这个基本的HTML结构:jQuery的:使用遍历嵌套元素每个

<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的同时也想知道如果我在a或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,它应该工作。

0

你可以使用.closest方法:

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

如果你关心,那么我会分开选择这样的:

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

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

您可以检查类的父元素内你的函数,以确定如果你在“A”或“b”

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

因此,父类var目录应该有eithe值r'a'或'b'