翻閱古今
2019-12-09 14:35:39
我有2種方法可以創(chuàng)建<div>using jQuery。要么:var div = $("<div></div>");$("#box").append(div);要么:$("#box").append("<div></div>");除了可重用性以外,使用第二種方式的缺點(diǎn)是什么?
3 回答

慕村9548890
TA貢獻(xiàn)1884條經(jīng)驗(yàn) 獲得超4個(gè)贊
我個(gè)人認(rèn)為,與性能相比,代碼的可讀性和可編輯性更為重要。無(wú)論您發(fā)現(xiàn)哪一個(gè)更容易看,它都是您出于上述因素而選擇的一個(gè)。您可以將其編寫為:
$('#box').append(
$('<div/>')
.attr("id", "newDiv1")
.addClass("newDiv purple bloated")
.append("<span/>")
.text("hello world")
);
而您的第一個(gè)方法為:
// create an element with an object literal, defining properties
var $e = $("<div>", {id: "newDiv1", name: 'test', class: "aClass"});
$e.click(function(){ /* ... */ });
// add the element to the body
$("#box").append($e);
添加回答
舉報(bào)
0/150
提交
取消