2009-04-08 21 views

回答

258

把這個HTML代碼:

<div id="mydiv">Hello World</div> 

這樣做:

$('#mydiv').html('Aloha World'); 

會導致:

<div id="mydiv">Aloha World</div> 

做:

$('#mydiv').replaceWith('Aloha World'); 

會導致:

Aloha World 

所以html()替換元素的內容,而replaceWith()代替實際元素。

29

replaceWith()將替換當前元素,而html()只是替換內容。

請注意,replaceWith()實際上不會刪除元素,只是將其從DOM中刪除並將其返回給您的集合中。

彼得一個例子:http://jsbin.com/ofirip/2

+3

+1非常有用,它記下了replaceWith()並不實際刪除元素。我沒有想到這個! – Peter 2012-02-20 03:11:26

+0

-1,但它不是真的:( – Peter 2012-02-20 03:13:40

+2

)這是真的,它仍然存在。它不在DOM中,所以你不會看到它,但它仍然是一個有效的HTML片段。證明:http:// jsbin。 com/ofirip/2 – cgp 2012-02-20 03:36:33

2

老問題,但這可能有助於某人。

如果您的HTML無效,這些功能在Internet Explorer和Chrome/Firefox中的運行方式會有所不同。

清理您的HTML,它們將按照記錄工作。

(不關閉我的</center>我晚上花了我!)

3

有使用HTML()與replaceWith()jQuery函數有兩種方式。

<div id="test_id"> 
    <p>My Content</p> 
</div> 

1)HTML()與replaceWith()

var html = $('#test_id p').html();將返回 「我的內容」

var replaceWith = $('#test_id p').replaceWith();將返回 <p>My Content</p>整個DOM對象。


2)HTML( '值')與replaceWith( '值')

$('#test_id p').html('<h1>H1 content</h1>');會給你下面放出來。

<div id="test_id"> 
    <p><h1>H1 content</h1></p> 
</div> 

$('#test_id p').replaceWith('<h1>H1 content</h1>');會給你下面放出來。

<div id="test_id"> 
     <h1>H1 content</h1> 
</div> 
相關問題