开发者

Attach click event to span tag in HTML?

I have a 开发者_C百科div that contains many spans and each of those spans contains a single href.

How do I attach a click event to the a tag?


Your live selector would be div span a (an a somewhere inside a span that's somewhere inside a div). E.g.:

$('div span a').live('click', function() {
  // ...
});

If you want to limit it to only an a that's a direct child of a span which is a direct child of a div, that would be div > span > a (or div span > a for as that are direct children of spans anywhere in a div, etc.).

If you want to do this for just one specific div, replace div above with #the_id_of_the_div (or any other selector that will identify that specific div).


If there is a large number of anchors (a, or "hrefs" as the OP calls them) then this might be better to write using event delegation: attach a single click listener to the parent div and in the callback, find out which a originally fired the event.

$('#yourDiv').click(function (event)
{
    var $target = $(event.target);
    if($target.is('div>span>a')
    {
        // your callback logic here, where you can consider
        // $target to be analogous to $(this) in a non-delegated handler
    }
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜