jQuery replaceWith()每个元素的第一个 [英] jQuery replaceWith() each element with the first

查看:97
本文介绍了jQuery replaceWith()每个元素的第一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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小提琴! 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:

JavaScript:

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

推荐答案

您必须 .clone() 元素:

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

这篇关于jQuery replaceWith()每个元素的第一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆