2012-09-11 73 views
0

嘗試複製頁面上的第一個.postNav,並用它替換所有後續的導航。我已經簡化了它,邏輯似乎正確,但該函數只適用於傳遞字符串而不是元素。jQuery replaceWith()每個元素都帶有第一個

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)')); 
}); 
+0

「* ...所選元素,而不是被克隆代替從原先的位置被移動的目標。」 * - HTTP://api.jquery .COM/replaceWith – nbrooks

回答

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(); 
}); 
0
var replaceHTML = $('.postNav:first').html(); 
$('.postNav:gt(0)').each(function(){ 
    $(this).replaceWith(replaceHTML); 
}); 
相關問題