我最近偶然發現使用jQuery對象作爲參數html()
的作品。 Accordin到documentation,唯一可以接受的類型是htmlString
和function
但由於某些原因,以下仍然有效:爲什麼在html()中使用jQuery對象作爲參數工作?
var htmlString = '<span>hello world</span>';
var jQueryObject = $(htmlString);
$('div').html(jQueryObject);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
UPDATE:
看來我的代碼片段的機制可能被誤解了,所以提供這個幫助澄清。 html()
將成功取得任意 jQuery對象 - 無論它是如何構造的。你可以在下面看到,我只是選擇頂部div中的<span>
元素並移動它。在這種情況下,不會引入htmlString
。
$('button').on('click', function() {
$('#fill-me').html($('#move-me span'));
});
div {
height: 20px;
width: 100%;
border: 1px solid #000;
margin: 5px;
padding: 5px;
}
#move-me {
color: red;
}
#fill-me {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="move-me"><span>Hello World</span></div>
<div id="fill-me"></div>
<button>Click to Move HTML</button>
爲什麼這項工作專櫃文檔說什麼支持?我在文檔中錯過了什麼嗎?
%的[文件](http://api.jquery.com/Types/#htmlString):_「的字符串指定htmlString在jQuery文檔中,當它被用來表示一個或多個DOM元素時,通常被創建並插入到文檔中。當作爲jQuery()函數的參數傳遞時,如果字符串以開頭,則標識爲HTML)直到最後>字符被解析。「_ –
j08691
@ j08691他的問題是關於'.html(jQueryObject',而不是關於'$(htmlString)'的問題' – Barmar
@Barmar他的問題是關於爲什麼'.html()'接受當文檔狀態爲jQuery對象時,它接受'htmlString',並且顯示關於jQuery的文檔觀看一個'htmlString' – j08691