Javascript 从 jquery 中的段落中获取文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3552814/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting text from a paragraph in jquery
提问by satyajit
This might be a very simple thing in jquery but I am not able to figure it out. My html document has the following structure
这在 jquery 中可能是一件非常简单的事情,但我无法弄清楚。我的 html 文档具有以下结构
<div class="body">
<a href="/question?id=70"><p>This is the text I want to extract</p></a>
</div>
I tried this
我试过这个
$("body").find("a p").text()
but this does not seem to be working for me. I am able to get the paragraph object but not the text. I tested it with console.log with no use.
但这似乎对我不起作用。我能够获得段落对象,但不能获得文本。我用 console.log 测试它没有用。
回答by Nick Craver
What you have should be working (you can test it here), make sure you're running it when the DOM is ready though, like this:
您所拥有的应该可以正常工作(您可以在此处对其进行测试),请确保在 DOM 准备就绪时正在运行它,如下所示:
$(function() {
alert($("body").find("a p").text()); //or just $("a p").text()
});
If it runs earlier, the elements may not be ready, and your selector won't find any matches.
如果它更早运行,元素可能还没有准备好,并且您的选择器将找不到任何匹配项。
If you want to select the classbodymake sure to use ".body"instead of "body"(which would select the <body>element). Here's a version using the .classselector:
如果要选择类,请body确保使用".body"而不是"body"(这将选择<body>元素)。这是使用.class选择器的版本:
$(function() {
alert($(".body a p").text());
});
回答by jpluijmers
the .html() function retrieves a nodes inner html.
.html() 函数检索节点内部 html。
$('.body a p').html();
should do the trick
应该做的伎俩
回答by Jesse Dhillon
Not sure if this would cause a problem, but you have invalid markup. From "The global structure of an HTML document" by the W3C
不确定这是否会导致问题,但您的标记无效。来自W3C 的“ HTML 文档的全局结构”
Generally, block-level elements may contain inline elements and other block-level elements. Generally, inline elements may contain only data and other inline elements. Inherent in this structural distinction is the idea that block elements create "larger" structures than inline elements.
通常,块级元素可能包含行内元素和其他块级元素。通常,内联元素可能只包含数据和其他内联元素。这种结构区别的内在思想是块元素创建比行内元素“更大”的结构。
aelements are supposed to be contained by block elements like p, not the other way around.
a元素应该包含在块元素中,例如p,而不是相反。
回答by Mohsin Shoukat
here is your paragraph element in html or php file which is id assign tt
这是您在 html 或 php 文件中的段落元素,它是 id 分配 tt
<p id="tt">ALert Message </p>
var tt = $("#tt").text();
alert(tt);
working fine for jquery-3.1.1.js
为 jquery-3.1.1.js 工作正常

