简体   繁体   English

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

[英]jQuery: iterate over nested elements using each

i have this basic html structure: 我有这个基本的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>

now i want to iterate over all m's but also would like to know if i am in a or b. 现在我想迭代所有m,但也想知道我是在a还是b。 using basic jquery syntax each i fail to do find this out. 使用基本的jquery语法,我无法找到它。

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

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

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

同样的b,它应该工作。

If you care, then I'd separate the selectors like this: 如果你关心,那么我将这样的选择器分开:

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

$('.b .m').each(function(index) {
    // now I'm on .b items
});
$('.m').each(function(index) {
    this.parentNode.getAttribute( "class" );
});

例如,检查父级是.a

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

You could use the .closest method: 您可以使用.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");
}   

You can check the class of the parent element inside your function to identify if you are in 'a' or 'b' 您可以检查函数内部父元素的类,以确定您是否处于'a'或'b'

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

So, the parentClass var should have a value of either 'a' or 'b' 因此,parentClass var的值应为'a'或'b'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM