将元素的属性复制到javascript循环中的其他元素

时间:2013-01-19 04:24:42

标签: javascript jquery each

我在循环js中遇到了问题。我想将data-icon类的.nav值复制到li中的#item-control。反正用jquery解决它是否容易?

<div id="nav-container">
  <ul class="nav">
   <li data-icon="images/1.png">Item 1</li>
   <li data-icon="images/2.png">Item 2</li>
   <li data-icon="images/3.png">Item 3</li>
  </ul>
</div>

<div id="item-control">
  <li>Item Control 1</li>
  <li>Item Control 2</li>
  <li>Item Control 3</li>
</div>

我尝试了什么:

$(document).ready(function () {
    var a = 1;
    $('#container #nav-container ul.nav li').each(function () {
        var item_control = $(this).parent().parent().parent().find('#item-control li');
        item_control.addClass('item' + a);  //this is what I tried before adding data-icon attributes to #item-control li
        a++;
    });
});

1 个答案:

答案 0 :(得分:0)

var $navItems = $('.nav li'),
    $itemControlItems = $('#item-control li');
$.each($navItems, function(index, el) {
    $($itemControlItems[index]).data('icon', $(el).data('icon'));
});

Fiddle