JQuery,如何从父级获取循环中的属性

时间:2017-12-03 05:48:30

标签: javascript jquery loops

我遇到了数组和循环的问题,我想从数组中设置两个属性(yt到task和href到b b_yt),例如:

                              //from
<div class="task" yt="">
    <div class="button">
         <a class="b b_yt" href="">
    </div>
</div>

<div class="task" yt="">
    <div class="button">
         <a class="b b_yt" href="">
    </div>
</div>

<div class="task" yt="">
    <div class="button">
         <a class="b b_yt" href="">
    </div>
</div>

                              //to
<div class="task" yt="a">
    <div class="button">
         <a class="b b_yt" href="a">
    </div>
</div>

<div class="task" yt="b">
    <div class="button">
         <a class="b b_yt" href="b">
    </div>
</div>

<div class="task" yt="b">
    <div class="button">
         <a class="b b_yt" href="b">
    </div>
</div>

我的js:

        var arr = ['a','b','c'];

        var allBtn = document.querySelectorAll('a.but.b_yt');
        var allDiv = document.querySelectorAll('div.task');

        allDiv.forEach(function(item, i){
            item.setAttribute('yt', arr[i]);
        });  
        //This is changing yt attribute in task and it is working

如何从div.task获取yt属性值并在a.but b_yt中将其设置为href,当然是在循环中?

1 个答案:

答案 0 :(得分:0)

allDiv.forEach(function(item, i){
            $(item).closest("task")[0].setAttribute('yt', arr[i]);
        }); 

使用最近的jquery函数来获取父类名称的父项。