replaceWith()没有删除原始元素

问题描述:

是否有一个类似于replaceWith()的jQuery函数用一个新元素替换元素,而不会破坏原始元素(只是隐藏它)。replaceWith()没有删除原始元素

+0

http://stackoverflow.com/questions/918792/use-jquery-to-change-an-html-tag –

,你可以这样做:

<button>replace</button> 
<div class="toReplace">your first content</div > 
<div class="toReplace" style="display: none">your second content</div > 

然后JS:

$("button").click(function() { 
    $("toReplace").toggle(); 
}); 

使用的hide[API Ref]after[API Ref]组合:

$('#oldElem').hide().after($('#newElem')); 

什么这样的事情?

$(this).before("this is what I'm inserting").hide(); 

只需在元件之前或之后插入元件,然后隐藏元件本身。试试这个

$("element").hide().after($("newElement")); 

如果你想用CSS来隐藏它.after()像以前一样只是调用.hide()

$('#theolddiv').hide().after('$(<div>The new div</div>')); 

如果你想完全从DOM中删除,而不是仅仅用CSS隐藏它,但希望能够在DOM后重新插入,也许别的地方就算了,然后将其存储在像变量:

var $x = $('#theolddiv'); 
$x.replaceWith('<div>The new div</div>'); 
// Do stuff here, you can put $x back in the DOM if you want. 

这实际上使得复制o F中的对象,但它不够好:)

切换能见度在某些情况下可以正常工作,但首选的方法是克隆原始元素。例如:

var clone = $('#elementOne'); 
$('#elementToBeReplaced').replaceWith(clone); 

管理形式输入时,作为DOM不关心如果该元素是可见或不可见,这是特别有用的。