问题
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