jQuery-根据另一个元素的属性值将类添加到多个元素

时间:2015-10-21 19:28:30

标签: jquery

我有以下代码:

<div class=“item”>
    <div class=“title”>......</div>
    <div class=“description”>......</div>
    <div class=“link”>.
        <a href=“destination_1”> .... </a>
    </div>
</div>



<div class=“item”>
    <div class=“title”>......</div>
    <div class=“description”>......</div>
    <div class=“link”>.
        <a href=“destination_2”> .... </a>
    </div>
</div>



<div class=“item”>
    <div class=“title”>......</div>
    <div class=“description”>......</div>
    <div class=“link”>.
        <a href=“destination_3”> .... </a>
    </div>
</div>

我需要根据href的值为.title,.description和.link添加一个额外的类。这就是它应该是这样的:

<div class=“item”>
    <div class=“title dest1”>......</div>
    <div class=“description dest1”>......</div>
    <div class=“link dest1”>.
        <a href=“destination_1”> .... </a>
    </div>
</div>



<div class=“item”>
    <div class=“title dest2”>......</div>
    <div class=“description dest2”>......</div>
    <div class=“link dest2”>.
        <a href=“destination_2”> .... </a>
    </div>
</div>

....等等

谢谢

3 个答案:

答案 0 :(得分:1)

试试这个:

&#13;
&#13;
$('.item').children().addClass(function() {
    return $(this).addClass('dest' + $(this).parent().index());
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item">
    <div class="title">......</div>
    <div class="description">......</div>
    <div class="link">.
        <a href="destination_1"> .... </a>
    </div>
</div>



<div class="item">
    <div class="title">......</div>
    <div class="description">......</div>
    <div class="link">.
        <a href="destination_2"> .... </a>
    </div>
</div>



<div class="item">
    <div class="title">......</div>
    <div class="description">......</div>
    <div class="link">.
        <a href="destination_3"> .... </a>
    </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

根据您的目的地以及您希望如何将它们与您的课程配对,这可能是您正在寻找的目标:

$('a[href="destination_1"]').closest('.item').children().addClass('dest1');

在此处查看演示:http://jsfiddle.net/0w76dwc0/

答案 2 :(得分:0)

有些事情......

var items = $('body').find('.item');

items.each(function(){
    var self = $(this);
    var href = self.attr('href');

    if(//YOUR CONDITION with href//)
    {
        self.find('.title').addClass('dest1');
        self.find('.decription').addClass('dest1');
        self.find('.link').addClass('dest1');
    }

    // etc

});

并查看 j08691 所说的内容!