I need to be able to get the href (or somehow get 开发者_运维问答the target url) of any <a>
tag that is clicked even if it is wrapping another element. For example, you could ordinarily do:
$("document").click(function (event) {
url = event.target.href;
});
However, in this example, the <a>
wraps an <img>
, so the event target will not have the href
. Using parentNode
is no good either, because there is also a span around the img in the example:
http://jsfiddle.net/z7ZYw/
I cannot change the selector either.
So is there any way to get the href in this circumstance?
You're looking for jQuery's closest
method:
$(e.target).closest('a');
As a note, this can be done without jQuery aswell:
var href = (e.target.parentNode && e.target.parentNode.href) ? e.target.parentNode.href : e.target.href;
You need to bind only on anchor tags:
$("a[href]").click(function () {
console.log($(this).attr("href"));
});
精彩评论