Successive Click Events

I have a problem understanding a particular Javascript event script.

See http://jsfiddle.net/UFL7X/ for an illustration.

When I click on the yellow field for the first time, I expect that only the first-click event handler is called, and the large field turns green. But both event handlers are called (a large rectangular rectangle turns red), although the second handler did not exist at the time of the click (at least, I thought so).

How can this be explained?

+3
source share
2 answers

So what happens is that your event is seething with a house.

  • A click appears on div2
  • div2 The click function is called
  • he changes color div1
  • he assigns a click event to div1
  • div2 ( return true)
  • DOM
  • div1
  • div1 click

, , return false div2

: , JS , div2 100 , , div1 100 , .

(, , ):

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

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

, , # div2, # div1. , false # div2 . . jsFiddle : http://jsfiddle.net/mitchmalone/UFL7X/1/

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

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

Source: https://habr.com/ru/post/1788099/


All Articles