开发者

how to find an anchor tag is clicked on current document in jQuery

I want to attach a click event at the document level with

 $(document).click();

And on clicking the element i would like to find out whether it is an anchor tag. If it is a开发者_Go百科n anchor tag, then i will call a method to do something. How can that be done? Any idea?


You'll just have to check the event object's target.

$(document).click(function(e) {
  var targ;
  if (!e) var e = window.event;
  if (e.target) targ = e.target;
  else if (e.srcElement) targ = e.srcElement;

  if ($(targ).is('a')) {
    // do your stuff
  }
});

(cross-browser code for getting the event target from quirksmode)

Also, if you're going to attach also other event handlers to the links, make sure you use event.preventDefault instead of just returning false if you want to cancel the link's default action (see this question).


How about just attaching this function you want to call to all of the anchor tags directly?

$("a").click(function(){ alert("a link!") })


<a href="#anchor">Anchor</a>
<a href="link">Anchor</a>

<script type="text/javascript">
    $(document).click(function(event){
        if(event.target.nodeName === 'A'){
            alert('Anchor');
        } else{
            alert('Not an anchor');
        }
    });
</script>


@kkyy: What will not work, is, if you are trying to make a request on that click event of that anchor, in Safari (all, windows, iPhone, etc.) e.g. in your code:

if ($(targ).is('a')) {
    var img = new Image(1,1);
    img.onload = function(){};
    img.src = "http://www.google.com/images/logos/somelogo.png?" + new Date().getTime();
  }

If you watch the traffic through any sniffer, you won't see the request above in Safari. Yes, pretty lame!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜