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

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

本文关键字:什么 区别      更新时间:2023-09-26

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

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

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

$("<p>")将创建一个段落元素并返回它,而$("p")将选择dom中的所有段落元素并返回它。

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