最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Make onclick handler ignore clicks on links - Stack Overflow

programmeradmin4浏览0评论

I have a custom onclick handler for a block element (set up through jQuery's .click() method). This block element can contain links.

I'm fairly certain this is possible, so, how do I have the handler simply return if it was a link I clicked on (so that the link is visited without running my code)?

I have a custom onclick handler for a block element (set up through jQuery's .click() method). This block element can contain links.

I'm fairly certain this is possible, so, how do I have the handler simply return if it was a link I clicked on (so that the link is visited without running my code)?

Share Improve this question asked Sep 22, 2009 at 8:23 Ryan McCueRyan McCue 1,65814 silver badges23 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 7

Check the event object to see if the target is an anchor tag then return true:

$("div").click(function(eventObject){

    if($(eventObject.target).is("a"))
        return true;

    //run your code
});

inside your click event, you can check what the event target tagname is:

$("#myDiv").click(function(e) {
  if (e.target.tagName.toLowerCase() == "a") {
    return true; //link clicked
  } else {
    //run your usual div click code here...
  }
});

how about testing if the element is an anchor or not inside the on click function?

if(this.tagName() == "a")return true;

I didn't test it, check it and reply please

Checking the nodeName of event.target doesn't work if your links have descendent elements (e.g. <span> or <img>).

Instead, try walking up the tree from event.target (the deepest element) to event.currentTarget (the event the event handler was registered on) and checking whether any of those elements are clickable:

$("div").click(function(event) {
    if (clickableBetweenTargetAndCurrentTarget(event))
        return; // This click was probably already handled.
    doSomething();
});

function clickableBetweenTargetAndCurrentTarget(event) {
    for (var el = event.target; el && el != event.currentTarget; el = el.parentNode) {
        if (isClickable(el))
            return true;
    }
    return false;
}

function isClickable(el) {
    // TODO: Customize this as appropriate for your webpage.
    return el.nodeName == 'A' || el.nodeName == 'BUTTON';
}

Demo: http://jsbin./fojaco/2/

Note that you'll have to customize isClickable for your particular webpage; it's hard/impossible to tell whether an element is clickable in the general case.

An alternative approach would be to make sure that all clickable descendants call event.preventDefault(), then your click listener on the div only needs to check event.defaultPrevented (IE9+). Or the descendants could call event.stopPropagation(), as suggested on another answer, but calling stopPropagation can lead to subtle bugs.

发布评论

评论列表(0)

  1. 暂无评论