如何判断jQuery点击发生在哪个元素上?
问题描述:
我处理与jQuery的一个列表项点击:如何判断jQuery点击发生在哪个元素上?
$("#some_list li").click(function(event) {
// magic happens here
}
列表项的样子:
<li><input type='checkbox'>Some text<span class='info'>(?)</span></li>
我想有根据不同的行为是否内用户点击(? )或列表中的其他任何地方。如何检测用户点击了哪个元素?
答
像this
:
$(this)
所有事件处理程序中的元素的上下文中运行,所以this
将参照本地DOM对象触发事件的元素。
但是,这并不完全回答你的问题 - this
将是处理程序注册的元素。
要找到被点击的实际元素(可以是this
孩子),你应该写$(e.target)
答
我写了一个简单的jQuery代码来获取点击的链接的数量。
var temp_str='';
$(document).ready(function(){
$('a').click(function(e){e.preventDefault();});
$(document).click(function(e){
if($(e.target).data('count')==undefined)
$(e.target).data('count',0);
$(e.target).data('count',$(e.target).data('count')+1);
$('a').each(function(i,item){if($(item).data('count')!=undefined)temp_str+=$(item).html()+" : "+$(item).data('count')+"<br>";});
$('#helper').html(temp_str);
temp_str='';
});
});
+1,你应该只是澄清究竟在哪里。 – 2010-05-03 00:58:24