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

标签 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);
});

但结果是浏览器挂了:'(

最佳答案

您需要克隆该元素并将其添加到当前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

关于javascript - 在相同的上下文中复制相同的东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29887084/

相关文章:

javascript - javascript 错误或没有线索

javascript - React Native 不支持在 Windows 上开发(还)?

Javascript if else 初学者

javascript - jQuery .remove() 无法删除 JQuery var

jquery - 如何将 jquery 与 asp.net ajax 结合使用

php - 用户自定义样式是否可以与 document.ready + localStorage 一起使用?

javascript - 隐藏 HTML 标签上的溢出使浏览器跳转到页面顶部

CSS HTML : Centering divs

javascript - 如何动态设置 AJAX 加载栏的动画直至其达到 100%?

javascript - 聚类谷歌地图时删除图钉