1
<ul id ='foo'>
    <li><p>hello</p></li>
    <li><p>hello</p></li>
    <li><p>hello</p></li>
</ul>

$('#foo').delegate('li', 'click', function(event) {
    if (#foo) { 
      do 
    } else if (li) {
      do 
    }
});

我有很多对象,每页近 1000 个。我想通过在一个事件委托上处理每个父对象和子对象来减少事件绑定的数量。

我怎样才能做到这一点?上面的代码现在只适用于 li。

4

3 回答 3

0

用这个:

$('#foo').on('click', function(event) {
    var action_target = $(event.target);
    if (action_target.closest('li').length > 0) { /* an LI was clicked */ }
    else { /* Something else inside #foo was clicked */ }
}
于 2013-07-18T17:29:45.417 回答
0

Derek's suggestion is nice but not fully reliable since .closest('li') is likely to find a list item in which #foo might be contained. Besides, in this case .length > 0 will always be true.

That being said, there is no need to traverse up the DOM tree using .closest(). Indeed, we already know that the handler will be called only if #foo or one of its descendants is clicked, so, we just need to check whether the clicked element (event.target) is #foo (this) :

$('#foo').click(function (e) {
    if (e.target === this) {
        // #foo was clicked directly
    } else {
        // something inside of #foo was clicked
    }
});

However, .closest() could be useful to retrieve a particular element inside of #foo. Let's say we want the direct LI that was clicked in order to add a selected class to it :

$('#foo').click(function (e) {
    var item;
    if (e.target === this) {
        // #foo was clicked directly
    } else {
        // something inside of #foo was clicked
        // 3 options to find the related item :
        // option 1 - easy to read
        item = $(e.target).closest('#foo > li');
        // option 2 - useful if the container has no ID
        item = $(e.target).closest($(this).children());
        // option 3 - probably the fastest one
        item = e.target;
        while (item.parentNode !== this) item = item.parentNode;
        item = $(item);
        item.addClass('selected');
    }
});

Here is a demo : http://jsfiddle.net/wared/dE6Pj/.

Documentation : http://api.jquery.com/closest/.

于 2014-02-21T12:09:44.430 回答
0
$(document).delegate('ul', 'click', function(event) {
    console.log(event);
    if (event.target.nodeName == 'P') { 
      alert('p clicked'); 
    } else {
      alert('parent clicked'); 
    }
});

这将减少代表团的UL级别。喜欢#foo就换吧。ul

JSFIDDLE

于 2013-07-18T17:28:21.540 回答