jQuery用第一个替换每个元素的带()

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

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

HTML:

  

JavaScript的:

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

你必须.clone()元素:

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

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

 var $navs = $('.postNav'), $replaceWith = $navs.first(); $navs.not( $replaceWith ).replaceWith(function () { return $replaceWith.clone(); }); 
 var replaceHTML = $('.postNav:first').html(); $('.postNav:gt(0)').each(function(){ $(this).replaceWith(replaceHTML); });