admin管理员组

文章数量:1314216

I have an onclick event attached to a region in my page that causes a certain action to fire when the user clicks in it (naturally). I recently added an image to that region. When the user clicks on that image, I want another action to occur, and I do NOT want the action associated with the entire region to occur. However, I find that both events are, in fact fired when one clicks the image. How do I suppress the region-wide action when the image is clicked?

I have an onclick event attached to a region in my page that causes a certain action to fire when the user clicks in it (naturally). I recently added an image to that region. When the user clicks on that image, I want another action to occur, and I do NOT want the action associated with the entire region to occur. However, I find that both events are, in fact fired when one clicks the image. How do I suppress the region-wide action when the image is clicked?

Share Improve this question edited Dec 29, 2022 at 23:25 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Jun 8, 2009 at 16:12 ep4169ep4169 2,3652 gold badges17 silver badges20 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

The issue you are running into is known as event bubbling. The click event of the image bubbles up to all parent elements of that node. You want to cancel bubbling.

The best way to do this that works across all browsers is by using a JavaScript framework. jQuery has a very simple way to do this. Other frameworks have similar mechanisms to cancel bubbling, I just happen to be most familiar with jQuery.

For example, you could do something like this in jQuery:

$('img').click(function () {
    // Do some stuff

    return false;// <- Cancels bubbling to parent elements.
});

Darit is correct, you need to stop the event from bubbling (propagating):

function imgEventHandler(e) {
    // ^notice: pass 'e' (W3C event)

    // W3C:
    e.stopPropagation();

    // IE:
    if (window.event) {
        window.event.cancelBubble = true;
    }

}

In the event handler for the image do

event.cancelBubble = true;

and then at the end do

return false;

本文标签: javascriptMultiple events firing from single actionStack Overflow