【问题标题】:jQuery replaceWith() each element with the firstjQuery replaceWith() 每个元素的第一个
【发布时间】:2012-09-03 22:31:40
【问题描述】:

试图复制页面上的第一个.postNav 并用它替换所有后续导航。我已经简化了它,逻辑似乎正确,但是该函数仅在我传递字符串而不是元素时才有效。

JS 小提琴! http://jsfiddle.net/cwMhh/1/

HTML:

<nav class="postNav">
    <ul>
        <li><a href="#pageHeader">link to header</a></li>
        <li><a href="#one">link to other posts</a></li>
        <li><a href="#two">link to other posts</a></li>
        <li><a href="#three">link to other posts</a></li>
        <li><a href="#four">link to other posts</a></li>
        <li><a href="#five">link to other posts</a></li>
    </ul>
</nav>

JavaScript:

$('.postNav:gt(0)').each(function(){
    $(this).replaceWith($('.postNav:eq(0)'));
});

【问题讨论】:

标签: jquery replace element each nav


【解决方案1】:

你必须.clone()元素:

$('.postNav:gt(0)').replaceWith(function () {
    return $('.postNav:first').clone();
});

为了更好的性能,缓存选择器:

var $navs = $('.postNav'),
    $replaceWith = $navs.first();

$navs.not( $replaceWith ).replaceWith(function () {
    return $replaceWith.clone();
});

【讨论】:

    【解决方案2】:
    var replaceHTML = $('.postNav:first').html();
    $('.postNav:gt(0)').each(function(){
        $(this).replaceWith(replaceHTML);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 2021-05-26
      • 1970-01-01
      • 2016-05-27
      • 2021-08-30
      • 2011-11-07
      • 2014-03-25
      相关资源
      最近更新 更多