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

时间:2021-08-11 18:03:11

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. using basic jquery syntax each i fail to do find this out.

现在我想遍历所有的m,但也想知道我是在a还是b中,使用基本的jquery语法我都没能找到。

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

7 个解决方案

#1


8  

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

美元(这).parent().hasClass(“a”)或美元(这).parent().hasClass(“b”)

#2


1  

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

And same for b, it should work.

对b也是一样,应该可以。

#3


1  

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

#4


0  

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

#5


0  

For example, check the parent is .a

例如,检查父结点是a

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

#6


0  

You could use the .closest method:

你可以用最接近的方法:

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

#7


0  

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'的值

#1


8  

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

美元(这).parent().hasClass(“a”)或美元(这).parent().hasClass(“b”)

#2


1  

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

And same for b, it should work.

对b也是一样,应该可以。

#3


1  

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

#4


0  

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

#5


0  

For example, check the parent is .a

例如,检查父结点是a

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

#6


0  

You could use the .closest method:

你可以用最接近的方法:

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

#7


0  

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'的值

相关文章