當HTML作爲參數傳入時,jQuery的replaceWith()和html()函數有什麼區別?jQuery的replaceWith()和html()之間有什麼區別?
128
A
回答
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
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>
0
它也可能是有用的知道,.empty().append()
也可以用來代替.html()
。在下面顯示的基準測試中,速度更快,但前提是您需要多次調用此函數。
相關問題
- 1. $ .replaceWith()和$ .remove + $ .appendTo之間的區別?
- 2. 「層」和「層」之間有什麼區別?
- 3. Tableau和QlikView之間有什麼區別
- 4. Microsoft.CompilerServices.AsyncTargetingPack和Microsoft.Bcl.Async之間有什麼區別?
- 5. @Entity和@embeddable之間有什麼區別
- 6. ContentObservable和DataSetObservable之間有什麼區別?
- 7. touchmove和gesturechange之間有什麼區別?
- 8. :notification.flags和notification.defaults之間有什麼區別?
- 9. proc和lambda之間有什麼區別?
- 10. :: after和after之間有什麼區別?
- 11. read()和io.read()之間有什麼區別?
- 12. Request()和Request.Form()之間有什麼區別?
- 13. WebServiceBinding.EmitConformanceClaims和WebServiceBinding.ConformanceClaims之間有什麼區別?
- 14. getA()和this.getA()之間有什麼區別?
- 15. (int)和intval()之間有什麼區別?
- 16. set_value和= pandas之間有什麼區別
- 17. * zoom和zoom之間有什麼區別?
- 18. {0}和「」之間有什麼區別?
- 19. typedef和using之間有什麼區別?
- 20. 「」和「'之間有什麼區別?
- 21. STDIN和tty之間有什麼區別?
- 22. +和%之間有什麼區別?
- 23. sysfs_create_file()和sysfs_create_group()之間有什麼區別?
- 24. Lazy.Force()和Lazy.Value之間有什麼區別
- 25. -existingObjectWithID:error:和-objectWithID之間有什麼區別?
- 26. ReleaseFloatArrayElements和DeleteLocalRef之間有什麼區別
- 27. AutomationProperties.AutomationID和AutomationProperties.Name之間有什麼區別?
- 28. gets()和getc()之間有什麼區別?
- 29. _id:ObjectID和String之間有什麼區別?
- 30. @ResponseBody和HttpServletResponce之間有什麼區別
這幫了我!我試圖用jquery動態地改變標籤的文本,這個線程肯定幫助了我。謝謝! – 2015-09-15 19:13:34