jQuery:使用each迭代嵌套元素

5

我有一个基本的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 语法 each,我无法找到这个信息。

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

8

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

该代码片段用于判断当前元素的父元素是否具有类名"a"或"b"。

1
if($(this).parent().hasClass('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
$('.m').each(function(index) {
    this.parentNode.getAttribute( "class" );
});

0
例如,检查父元素是否为.a
if($(this).parent().is('.a'))

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");
}   

0

你可以在函数中检查父元素的类别,以识别你所处的是 'a' 还是 'b'

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

所以,parentClass变量的值应该是'a'或'b'


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接