开发者

jQuery: delegating clicks to elements that contain other elements

开发者 https://www.devze.com 2022-12-25 03:32 出处:网络
So i get the gist of $.delegate and I know why it\'s doing what it\'s doing, but I\'m wondering if there is a work around.

So i get the gist of $.delegate and I know why it's doing what it's doing, but I'm wondering if there is a work around.

I have link elements that contain spans like so:

<a href='#'>
    <span>Person Name</span>
    <span>Person Info</span>
</a>

I use the following code in jQuery for event delegation:

containerElement.delegate('click','a',function(){...});

The trouble is that this only triggers when I click on white space not occupied by a span. I know it does this because delegate simply compares the event tar开发者_开发问答get to 'a' to check if it should fire the delegate, however I want to include the spans as well, pretty much anything inside the <a>...</a>

what do?


Based on your comment I think you're looking for the following:

target.is('a, a > *');

.. or something similar.


you have written it the other way around. the first argument is the selector and the second one is the event name

$('body').delegate('a', 'click', function() { alert('hi'); });


Have you tried jquery live?

http://api.jquery.com/live/

It's built in delegation.


Like, vinhboy suggests, I'd use

$("a").live("click", myFunction);

function myFunction()
{
   alert("Hello");
}

In fact, give your a tags a class such as "myLink" and then perform on that

$("a.myLink").live("click", myFunction);

function myFunction()
{
   alert("Hello");
}
0

精彩评论

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