2013-11-20 22 views
1

我試圖抓住這個HTML的文本部分:使用jQuery從<a>元素中選擇文本?

<li class="location"><a href="#">Some Text</a></li> 

與這個jQuery:

$('.location').off('click').click(function() { 
alert($(this).children('a')[0].text()); 
} 

所以我警告顯示 「一些文本」。我只是不確定它爲什麼不起作用。

回答

4

.text()方法由jQuery包裝元素提供,children('a')[0]給出了一個沒有該方法的DOM元素。

使用的text()吸氣格式返回給定一組的第一個元素的文本內容是什麼,你正在尋找

$('.location').off('click').click(function() { 
    alert($(this).children('a').text()); 
}); 
+0

謝謝,我實際上結束了在我的代碼的另一部分有一個小錯誤,但你的答案是非常有用的這個例子。 –

0

嘗試

$('.location').off('click').click(function() { 
alert($(this).children('a').html()); 

});