开发者

Get href of wrapping anchor on click

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"));
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜