[英]Using jQuery, how do I get the text value of an element?
how do I retrieve the text between the href tag? 如何检索href标签之间的文本?
<a href="blah">GET THIS TEXT</a>
It is wrapped in this DOM: 它包含在这个DOM中:
<div class="c1">
<div class="c2"><a href="#">GET THIS TEXT</a>
</div>
</div>
You are looking for the text()
property: 您正在寻找
text()
属性:
$('a', 'div.c2').text();
The reason div.c2
is defined as the second argument is because it would then be the context
of the selector. div.c2
被定义为第二个参数的原因是因为它将成为选择器的context
。 By default jQuery searches the entire document when you use $()
, by specifying div.c2
it is only going to search inside of <div>
's with a class of c2. 默认情况下,当你使用
$()
,jQuery会搜索整个文档,通过指定div.c2
它只会在一个c2类的<div>
搜索。
Keeping this in mind, you could also rewrite the above like this: 记住这一点,你也可以像这样重写上面的内容:
$('div.c2 a').text();
Most people prefer this because it is the syntax that you would use to select this element in a CSS stylesheet. 大多数人更喜欢这个,因为它是用于在CSS样式表中选择此元素的语法。 However, jQuery then has to figure that out.
但是,jQuery必须弄清楚这一点。 You could even do:
你甚至可以这样做:
$('div.c2').find('a').text();
However, I prefer the context method as I feel it is cleaner and marginally faster, not that it matters. 但是,我更喜欢上下文方法,因为我觉得它更干净,速度更快,而不是重要。
There is also the html()
property, which gets the contents, including HTML . 还有
html()
属性,它获取内容, 包括HTML 。
So if your link was like this: 所以,如果您的链接是这样的:
<a href='#'><b>Hi There</b></a>
Then: 然后:
$('a').text(); // would return Hi There
$('a').html(); // would return <b>Hi There</b>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.