简体   繁体   English

从li内的div获取类并添加到同一个li

[英]Get class from div inside an li and add to same li

Get class from div inside an li and add to the same li. 从li内的div获取类并添加到相同的li。

The list items look similar to this: 列表项与此类似:

<li class="original">
<div id="one" class="text">foo</div>
<div id="two" class="photo">foo</div>
<div id="three" class="video">foo</div>
</li>

<li class="original">
<div id="one" class="text">foo2</div>
<div id="two" class="photo">foo2</div>
<div id="three" class="video">foo2</div>
</li>

...

I need to grab the class from each of the list item's divs with an id of "three" and add it to the parent li's class. 我需要从列表项的每个div中获取ID为“ 3”的类,并将其添加到父级li的类中。 So, after the code runs the list will look like this: 因此,代码运行后,列表将如下所示:

<li class="original video">
<div id="one" class="text">foo</div>
<div id="two" class="photo">foo</div>
<div id="three" class="video">foo</div>
</li>

<li class="original text">
<div id="one" class="video">foo2</div>
<div id="two" class="photo">foo2</div>
<div id="three" class="text">foo2</div>
</li>

I tried something like this but it only updates the first list item: 我尝试过类似的操作,但是它只会更新第一个列表项:

$("#three").each(function(i) { 
    var newclass = $(this).attr("class");                   
   $(this).parent().addClass(newclass);
});

Thanks in advance for your help! 在此先感谢您的帮助!

If you are stuck with the repeating ID's 如果您坚持使用重复ID

 $('[id="three"]').each(function(){  
     $(this).parent().addClass( this.className);

})

You can't have multiple elements with the same ID. 您不能有多个具有相同ID的元素。 In this case, jquery each is doing the correct thing and finding the first ID then stopping. 在这种情况下,每个jquery都在做正确的事情并找到第一个ID,然后停止。 You can fix this by using the class instead: 您可以改用类来解决此问题:

<li class="original video"><div class="text one">foo</div></li>
<li><div class="photo two">foo</div></li>
<li><div class="video three">foo</div></li>

<li class="original"><div class="video one">foo2</div></li>
<li><div class="text two">foo2</div></li>
<li><div class="photo three">foo2</div></li>

Then the jquery: 然后是jQuery:

$(".three").each(function(i) { 
var newclass = $(this).attr("class");                   
$(this).parent().addClass(newclass);
});

here is another solution you might want to take a look: demo 这是您可能要看的另一种解决方案: 演示

here is the JS code (After fixing the broken HTML issue people commented above but keeping the duplicate IDs) 这是JS代码(解决了上面提到的人破碎的HTML问题之后,但保留了重复的ID)

$(document).ready(function(){

    $('.original').each(function(i) {
    var div = $(this).find('div').eq(2);
    var newclass = $(div).attr("class");                   
   $(this).addClass(newclass);
});
    });​

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

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