从锚标记中获取文本

时间:2010-10-06 09:42:51

标签: jquery jquery-selectors

我有以下锚标记

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

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

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

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

2 个答案:

答案 0 :(得分:70)

使用.text()

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

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

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

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

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

然后会有:

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

答案 1 :(得分:0)

在使用上面提到的.text()时,我得到了代码中所有锚标签的文本:

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:

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

输出:

  • 第一项
  • 第二项
  • 第三项
相关问题