简体   繁体   English

使用jQuery,如何获取元素的文本值?

[英]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>

I think that .text() or .html() will work, depending on whether you don't or do want any markup that appears inside the tag. 我认为.text().html()将起作用,具体取决于你是否不想或者想要在标签内出现任何标记。

var txt = $('div.c2 > a').text();

var html = $('div.c2 > a').html()

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

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