我有一個跨度:
<span class="test"> target_string </span>
且事件,即開槍點擊頁面的任何元素。
$('body').click(function(event){
if ($(event.target).attr('class') == 'test'){
alert(???);
}
}
如何獲取target_string值?
我有一個跨度:
<span class="test"> target_string </span>
且事件,即開槍點擊頁面的任何元素。
$('body').click(function(event){
if ($(event.target).attr('class') == 'test'){
alert(???);
}
}
如何獲取target_string值?
使用$(event.target).text()
來獲取文本。
嘗試以下,
$('body').click(function(event){
var $targ = $(event.target);
if ($targ.hasClass('test')){
alert($targ.text());
}
}
可能更有效地從身體委託:
$('body').on('click', '.test', function(event){
alert($(this).text())
});
Thx的答案,這可能會有所幫助。 – mol
不知道,如果你打算與該事件處理程序內的其他要素的工作,除了那些有一類測試,但這可能更簡潔:
$('.test').click(function(event){
alert($(this).text());
});
爲什麼不只是'$(this)'? – zerkms
@zerkms因爲'$(this)'會引用body。 –
@zerkms:該事件綁定到「body」。 'this'將是'body'',而不是被點擊的元素。 –