[英]Element creation in jQuery; create, wrap, append
比較快的一個;
我正在動態創建一些元素,並將它們附加到另一個元素。
$element = $('<input />', {
// attributes
}).add('<label />', {
// attributes
});
這會產生<input /><label></label>
及其各自的屬性和內容。 我只是想把它包裝在一個<div>
中,並認為會有一種同樣干凈的方法,但我似乎無法讓以下工作:
$element = $('<input />', {
// attributes
}).add('<label />', {
// attributes
}).wrapAll('<div />');
如果我console.log()
我的$element
,它只是<input>
和<label>
。 我也試過
$element = $($('<input />', {
// attributes
}).add('<label />', {
// attributes
})).wrapAll('<div />');
分別選擇要附加的<input>
和<label>
元素,並應用.wrapAll()
,但這也不起作用,導致與上述相同。
我接近了嗎? 我應該只是 go 另一條路線嗎?
感謝@mu,最終得到了以下結果
$element = $('<div />').append($('<input />', {
// attr
}).add('<label />', {
// attr
}));
哦jQuery; 七百萬種方法來做同樣的事情,有時你想不出一個。
編輯
只是為未來的訪客添加; append
方法也可以采用數組:
$('<div />').append([
$('<div />'),
$('<div />'),
$('<div />'),
]);
這將產生:
<div>
<div></div>
<div></div>
<div></div>
</div>
所以你不需要鏈接調用append()
。
element = $('<div></div').html($('<input />', {
// attributes
}).add('<label />', {
// attributes
}));
如果我理解正確,我想你可能想使用.appendTo()
而不是.wrapAll()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.