Disable the onclick event of a parent element

后端 未结 5 1972
清酒与你
清酒与你 2021-01-07 05:13

Let\'s say I have an element with an onclick event, and another element inside it, how do I disable the onclick for the child element?

Example:

5条回答
  •  梦毁少年i
    2021-01-07 05:59

    Can I suggest this anwser I provided in a similar problem?

    Above I copied my original answer:


    I had a very similar problem to your first question. But instead a

    and a checkbox it was a table. Look at my NON WORKING code:

    Cell_1 Cell_2 Cell_3

    Clicking on Cell_1 or Cell_2, my code works as I expected, but when clicking on Cell_3 not, because it showed 2 alerts.

    The first one was:

    "I expect this alert only when Cell_3 is clicked"

    and the second one was:

    I expect this alert when Cell_1 or Cell_2 are clicked but not Cell_3.

    Google-ing how I could manage that, I found this briliant post on Quirksmode.

    Well, putting it simply, I could solve the puzzle this way:

    Cell_1 Cell_2 Cell_3

    And the Javascript:

    function Cell_3Alert(e) {
      alert('I expect this alert only when Cell_3 is clicked');
    
      if (!e) var e = window.event; 
      e.cancelBubble = true;
      if (e.stopPropagation) e.stopPropagation();
    }
    

    I've tested and it worked on FireFox 3.6+, IE6+ and Chrome.

    Hope it Helps!

    提交回复
    热议问题