<分区>
追加有很多种方法
我有 3 个例子:
$(".test1").append("<div>content#1</div>");
$("<div>content#2</div>").appendTo(".test2");
$("<div>", { text : "content#3" }).appendTo(".test3");
我觉得
- 最简单
- 是一样的...
- 是???
你能告诉我应该做哪一个吗?告诉我一些坏事,好事...
<分区>
追加有很多种方法
我有 3 个例子:
$(".test1").append("<div>content#1</div>");
$("<div>content#2</div>").appendTo(".test2");
$("<div>", { text : "content#3" }).appendTo(".test3");
我觉得
你能告诉我应该做哪一个吗?告诉我一些坏事,好事...
最佳答案
更多的是上下文而不是哪个更好。
您只会在非常极端的情况下看到性能差异,而不是您在典型网站上会注意到的东西。
本质上它们具有相同的目的:即将一个元素 append 到另一个元素中。
.append()
之间的区别和 .appendTo()
一旦您进行方法链接,就会显示自己。
var $whatIsThis = $(".test1").append("<div>content#1</div>");
$whatIsThis
仍将是 $(".test1")
.
var $whatIsThis = $("<div>content#1</div>").appendTo(".test1");
$whatIsThis
而是 <div>
你刚刚创建。
正如我提到的方法链,这里有一个例子
下面这个会隐藏.test1
.自新<div>
将在其中,两者最终都将不可见。
$(".test1") // this is me
.append("<div>content#1</div>")
.hide(); // hide me, I'm .test1
下面这个只会隐藏新的 <div>
你 append 到.test1
.
.test1
和里面的任何东西 .test1
应该保持可见。
$("<div>content#1</div>") // this is me
.appendTo(".test1")
.hide(); // hide me, I'm the new <div>
关于javascript - HTML 追加 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16238315/