jQuery replaceWith() each element with the first

不打扰是莪最后的温柔 提交于 2019-12-12 04:33:41

问题


Trying to copy the first .postNav on the page and replace all subsequent navs with it. I've got it simplified and the logic seems right, but the function only works when I pass a string, not the element.

JS Fiddle! 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)'));
});

回答1:


You have to .clone() the element:

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

For better performance, cache the selectors:

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


来源:https://stackoverflow.com/questions/12362175/jquery-replacewith-each-element-with-the-first

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!