2010-10-06 74 views
26

我有以下的锚标记从锚标记获取文本

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

我知道如何从锚拿得到的href:

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

但我怎么得到锚文本标记,即如何获得“Google”?

回答

61

使用.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>" 
+2

我怎样才能得到只有谷歌? – 2015-09-28 08:15:48

+0

任何答案只能获得即时文本? – 2016-09-02 07:25:28

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()); 
}); 

OUTPUT:

  • 第一项
  • 第二项
  • 第三项
+0

我只需要我点击的定位标记的文本值。 – 2017-07-07 10:02:22