admin管理员组

文章数量:1404561

I have a problem understanding a special Javascript event scenario.

For an illustration please see /

When the yellow box is clicked the first time, I would expect that only the first click event handler is called and the large box gets green. But both event handlers are called (the large box gets red), even though the second handler didn't exist by the time the click occurred (at least what I thought).

How can that be explained?

I have a problem understanding a special Javascript event scenario.

For an illustration please see http://jsfiddle/UFL7X/

When the yellow box is clicked the first time, I would expect that only the first click event handler is called and the large box gets green. But both event handlers are called (the large box gets red), even though the second handler didn't exist by the time the click occurred (at least what I thought).

How can that be explained?

Share Improve this question edited Jul 25, 2019 at 16:08 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Jan 27, 2011 at 4:37 medihackmedihack 16.6k21 gold badges91 silver badges140 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

So what is happening is that your event is bubbling up the dom.

  1. Click occurs on div2
  2. div2 click function is called
  3. it changes the colour of div1
  4. it assigns a click event to div1
  5. div2 click function ends (with an implicit return true)
  6. event bubbles up to parent in DOM
  7. div1 receives bubbled click event
  8. div1 click function is called

if you dont want this to happen then you need to return false in your click handler for div2

EDIT: Please note that the way you are organising your JS may not be the best because if I click div2 100 times that means that div1 now has 100 click events that will run.

I suggest that you do it this way (keep in mind that I don't know what your requirements are):

$("#div2").click(function() {
    $("#div1").css("background-color", "green");
    return false;
});

$("#div1").click(function() {
    $("#div1").css("background-color", "red");
});

The reason for this is because when you click #div2 you are also tracking a click for #div1. This can be fixed by doing a return false after you change the color for the #div2 click. See this jsFiddle for a working version: http://jsfiddle/mitchmalone/UFL7X/1/

$("#div1").live("click", function() {
    $("#div1").css("background-color", "red");
});

$("#div2").live("click", function() {
    $("#div1").css("background-color", "green");
    return false;
});

本文标签: javascriptConsecutive click eventsStack Overflow