[英]event.target points to a child element
When a user clicks on a <li>
-element or on a child element of it, I want to add a class to this <li>
-element. 当用户点击<li>
-element或其子元素时,我想向此<li>
-element添加一个类。
This works fine, but for performance enhancement I decided to bind this event to the <ul>
-element, so unbinding and binding this event is much faster in a list consisting of 1000 <li>
-elements. 这样可以正常工作,但是为了提高性能,我决定将此事件绑定到<ul>
-element,因此在包含1000个<li>
-elements的列表中,取消绑定和绑定此事件要快得多。 The only change I thought I had to make was to replace this
with event.target
BUT event.target
can also refer to a child element of a list item or even to a grandchild. 我想我不得不做出的唯一改变是更换this
与event.target
但event.target
也可以指一个列表项目甚至一个孙子或一个子元素。
Is there an easy way to check this target element is part of a list item or do I need to walk the path from event.target
till I reach a <li>
element? 有没有一种简单的方法来检查这个目标元素是列表项的一部分还是我需要从event.target
走路径直到我到达<li>
元素?
This is what I had before I decided to bind an event to the <ul>
tag, which works but is not fast enough: 这是我在决定将事件绑定到<ul>
标签之前的情况,该标签有效但速度不够快:
$('#list li').mousedown(function(){
$(this).addClass('green');
});
And this is what I have now which doesn't work properly, mousedown on a child element doesn't give the <li>
another classname: 这就是我现在所做的不能正常工作,在子元素上的mousedown不会给<li>
另一个类名:
$('#list').mousedown(function(event){
if(event.target.nodeName == 'LI'){
$(event.target).addClass('green');
}
});
I wonder if my second way to achieve this is faster if there is not a simple solution to check if that target element is part of a list item... 我想知道如果没有一个简单的解决方案来检查目标元素是否是列表项的一部分,我的第二种实现方法是否更快...
You need to check if there is a LI tag in the parents of the target element. 您需要检查目标元素的父项中是否存在LI标记。
All of the common frameworks have a way of determining this, it is up()
in prototype, ancestor()
in YUI3, and looking at the JQuery docs, it seems like it has a parent()
, and parents()
function that you can use for this. 所有常见的框架都有一种方法可以确定这一点,它是原型中的up()
,YUI3中的ancestor()
,看看JQuery文档,看起来它有一个parent()
,而parents()
函数就是你可以用于此。
See: http://docs.jquery.com/Traversing 请参阅: http : //docs.jquery.com/Traversing
Haven't used JQuery, but it I assume checking for $(event.target).parent('li')
is the answer. 没有使用过JQuery,但是我假设检查$(event.target).parent('li')
就是答案。
Well, you could do all of this with the jQuery on tool: 好吧,你可以使用jQuery on工具完成所有这些:
$('#list li').on('mousedown', function() {
$(this).addClass('green');
});
You can read about what on does here: http://api.jquery.com/on/ 您可以在这里阅读有关的内容: http : //api.jquery.com/on/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.