$("<p>") 和 $("p") 有什么区别

What's the difference between $("<p>") and $("p")

我们目前在学校学习 jQuery,我不明白 $("<p>")$("p") 之间的区别。虽然我知道 $("p") 搜索所有 <p> 元素,但我在互联网上找不到任何关于 $("<p>") 的信息。

这是我们从老师那里得到的代码:

var p = $("<p>").text("This is section " + ($("p").size() + 1))
.attr("align", "right").css("color", "blue");

$("<p>") 将创建一个段落元素并 return 它,而 $("p") 将 select dom 和 [=23] 中的所有段落元素=]它。

var p = $("<p>").text("This is section " + ($("p").size() + 1))
.attr("align", "right").css("color", "blue");

这段代码可以像下面这样拆解,

var p = $("<p>"); //created a new Paragraph element
p.text("This is section " + ($("p").size() + 1)); //set text that displays the count of the created paragraph element.
p.attr("align", "right"); //set its attribute.
p.css("color", "blue"); //set its color.

也是你的老师,不应该推荐你们使用 .size() 因为它已经被弃用了。请改用 .length