开发者

Delegate handler and inner children clicked

开发者 https://www.devze.com 2023-01-13 19:07 出处:网络
I have the following: <ul id =\'foo\'> <li><p>hello</p></li> <li><p>hello</p></li>

I have the following:

<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) {
    var target = $(event.target);
    console.log(target);   
});

the click handler gets called whenever one of the inner p elements gets clicked, as well as the parent li elements.

How can I get a pointer to the parent li element, regardless of which inner child element was clicked? For example, my real li elements look like:

<li>
  <p>one</p>
  <div>
    <p>two</p>
  </div>
</li>

so I'm finding I have to have several checks to get back up to the parent li that was clicked. Is there a way to just select the parent of a type like:

$('#foo').delegate('li', 'click', function(event) {
    var target = $(event.target).('li');
    c开发者_如何转开发onsole.log(target);   // will always be parent li element itself?
});

Thanks


In the handler, this will refer to the li element.

$('#foo').delegate('li', 'click', function(event) {
    var target = $(this);
    console.log(target);   // will always be parent li element itself?
});


var target = $(this) should be one way--that's how I usually do it. $(event.target).parents("li") would be another, but you might pick up more than you expect.

0

精彩评论

暂无评论...
验证码 换一张
取 消