I have a 开发者_C百科div
that contains many spans
and each of those span
s 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 a
s that are direct children of span
s 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
}
});
精彩评论