jQuery 从锚标签获取文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3871228/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:15:34  来源:igfitidea点击:

Get text from anchor tag

jqueryjquery-selectors

提问by oshirowanen

I have the following anchor tag

我有以下锚标记

<a href="http://www.google.com/">Google</a>

I know how to get the href from an anchor take:

我知道如何从锚点获取href:

alert($(this).attr("href"));

But how do I get the text from the anchor tag, i.e. how do I get "Google"?

但是如何从锚标记中获取文本,即如何获取“Google”?

回答by Nick Craver

Use .text()for this:

使用.text()此:

alert($(this).text());

If you wanted the markup (.text()removes tags and such), use .html()

如果您想要标记(.text()删除标签等),请使用.html()

alert($(this).html());

In thiscase there's no difference, if instead you had this:

这种情况下没有区别,如果你有这个:

<a href="http://www.google.com/">Google <span>(External)</span></a>

Then there would be:

那么就会有:

$(this).text() //"Google (External)"
$(this).html() //"Google <span>(External)</span>"

回答by Sumit Prashant

On using the .text() as mentioned, I got the text of all the anchor tags combined in my code:

如上所述,在使用 .text() 时,我得到了代码中组合的所有锚标记的文本:

HTML:

HTML:

<div class="col-sm-2 jumbotron jumbotronUserRaces list-group list-group-
userRaces" id="listGroupUserRaces">
                <a href="" class="list-group-item active">First item</a>
                <a href="" class="list-group-item">Second item</a>
                <a href="" class="list-group-item">Third item</a>
            </div> 

JS:

JS:

$("#listGroupUserRaces").click(function () {
   alert($(this).text());
});

OUTPUT:

输出:

  • First item
  • Second item
  • Third item
  • 第一项
  • 第二项
  • 第三项