简体   繁体   English

P标签的jQuery选择器

[英]JQuery selector for the P tag

I have a problem with selecting all the <P> tags in an HTML document using the Jquery library. 我在使用Jquery库选择HTML文档中的所有<P>标签时遇到问题。
This is a part from my HTMl: 这是我的HTMl的一部分:

<p> This whole page is just for developmental purposes only, so feel free to do whatever you want </p>
<p> Эта страница - только в целях развития. Так, чувствовать себя вправе сделать все, что хотите</p>

and this is my JS: 这是我的JS:

$(function(){
     console.log($("p").html());
})

but when it comes to the output it gives me only the first paragraph, I can't understand why it selects only one elements and not all elements with the P tag, i would be very grateful if someone shows me where the problem is. 但是当涉及到输出时,它只给我第一段,我不明白为什么它只选择一个元素而不选择带有P标签的所有元素,如果有人向我展示问题所在,我将不胜感激。

That's because .html() gets the value of the first element. 这是因为.html()获得第一个元素的值。 See the docs 查看文件

You can do an iteration using .each() 您可以使用.each()进行迭代

$("p").each(function() {
    console.log($(this).html())
});

Per the jQuery documentation for the .html() method : 根据.html()方法jQuery文档

Get the HTML contents of the first element in the set of matched elements or set the HTML contents of every matched element. 获取匹配元素集中第一个元素的HTML内容,或设置每个匹配元素的HTML内容。

(emphasis mine) (强调我的)

When using the method as a getter, it is designed to return the content of only the first element in the collection. 当将该方法用作getter时,它被设计为返回集合中第一个元素的内容。 When used as a setter, it operates on the whole collection. 当用作设置器时,它将对整个集合进行操作。

如果要从所有 <p>标记中获取内容,则可以使用.map()然后通过.join()遍历它们。

console.log($("p").get().map(p => $(p).html()).join(" "));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM