在相同的上下文中复制相同的东西

时间:2015-04-27 04:13:57

标签: javascript jquery html css

我有一个jquery的问题我有2个不同的图标集,每个我想要同样的事情:

我的主要代码是

  <ul>
      <li>
          <a href="">
              <i class="fa fa-facebook"></i>
          </a>
      </li>

       <li>
          <a href="">
              <i class="fa fa-twitter"></i>
          </a>
      </li>
   </ul>

加载到浏览器

后我想要的是什么
  <ul>
      <li>
          <a href="">
              <i class="fa fa-facebook"></i>
              <i class="fa fa-facebook"></i>
          </a>
      </li>

       <li>
          <a href="">
              <i class="fa fa-twitter"></i>
              <i class="fa fa-twitter"></i>
          </a>
      </li>
   </ul>

我试图使用

var socials = $("ul a");
socials.each(function ( index,elem ){
    var jumpIcons = $( this ).find("i");
    socials.append(jumpIcons);
});

但结果是浏览器被挂起:'(

3 个答案:

答案 0 :(得分:4)

您需要克隆并将元素添加到当前a

var socials = $("ul a");
socials.each(function (index, elem) {
    var jumpIcons = $(this).find("i");
    //first you need to clone the current element else, you are just repositioning the current `i` elemnet
    //then you need to append it to the current a element, not to all `a` element in the socials - this will cause a lot of iteration if there a lot of `ul a` elements in the page resulting in unresponisve page
    $(this).append(jumpIcons.clone());
});

演示:Fiddle

简化版

var socials = $("ul a");
socials.append(function (index, elem) {
    return $(this).find("i").clone();
});

演示:Fiddle

答案 1 :(得分:4)

您可以使用clone(),请参阅下面的代码

var socials = $("ul a");
socials.each(function ( index,elem ){
    var jumpIcons = $( this ).find("i").clone();//make clone of i
    $(this).append(jumpIcons);// use $(this) to get current element
}); 

答案 2 :(得分:3)

clone i a events append a var socials = $("li a"); socials.each(function ( index, elem ){ var jumpIcons = $( this ).find("i").clone(true, true); //remove true, true if you dont need the events $(this).append(jumpIcons); }); {{1}} {{1}} {{1}} {{1}}试试 -

{{1}}