2010-10-06 83 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