jQuery:使用每个嵌套元素迭代

时间:2011-08-26 14:45:07

标签: javascript 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,但也想知道我是在a还是b。 使用基本的jquery语法,我无法找到它。

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

7 个答案:

答案 0 :(得分:8)

$(this).parent().hasClass("a")$(this).parent().hasClass("b")

答案 1 :(得分:1)

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

同样对于b,它应该有用。

答案 2 :(得分:1)

如果你关心,那么我会将选择器分开:

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

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

答案 3 :(得分:0)

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

答案 4 :(得分:0)

例如,检查父级是.a

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

答案 5 :(得分: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");
}   

答案 6 :(得分:0)

您可以检查函数中父元素的类,以确定您是否处于'a'或'b'

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

因此,parentClass var的值应为'a'或'b'

相关问题