Why are these two bits of JavaScript not equivalent?

in jquery 1.4.2, ff 3.6.6:

The following code creates three divs that write messages to the firebug console, as you expected. However, if you uncomment the loop and comment out the three lines that do it manually, this will not work - when you click on the console, any of the div results will be "three".

Why are these two methods different from each other? In each of them, you use a selector to find an element and add an event to it.

<head>
<script type="text/javascript" src="/media/js/jquery.js"></script>
<script>

$( document ).ready( function() {

  $("#one").mouseenter(function(){console.log("one")})
  $("#two").mouseenter(function(){console.log("two")})
  $("#three").mouseenter(function(){console.log("three")})

  //  names=['one','two','three'];
  //  for (k in names){
  //    id=names[k]
  //    $("#"+id).mouseenter(function(){console.log(id)})
  //  }
})
</script>
</head>

<body>
  <span id="one">ONE</span>
  <p><span id="two">TWO</span></p>
  <p><span id="three">THREE</span></p>
</body>
+3
source share
2 answers

You will have a very common closure problem in a loop for in.

, , , mouseenter , id names.

, , . :

, factory:

function makeMouseEnterCallback (id) {  
  return function() {  
    console.log(id);
  };  
}

// ...

var id, k,
    names = ['one','two','three'];

for (k = 0; k < names.length; k++) {
  id = names[k];
  $("#" + id).mouseenter(makeMouseEnterCallback(id));
}

factory :

var id, k, 
    names = ['one','two','three'];

for (k = 0; k < names.length; k++) {
  id = names[k];
  $("#" + id).mouseenter((function (p_id) {  
    return function() {  
      console.log(p_id);
    };  
  })(id));
}

@d.m, , :

var k, 
    names = ['one','two','three'];

for (k = 0; k < names.length; k++) {
  (function() {
    var id = names[k];
    $("#" + id).mouseenter(function () { console.log(id) });
  })();
}

, for in , @CMS ( ). , ​​JavaScript.

+12

, , function(){console.log(id)}, id three.

, :

names=['one', 'two', 'three'];
for (var k in names) {
    (function() {
        var id = names[k];
        $("#"+id).mouseenter(function(){ console.log(id) });
    })();
}
+2

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


All Articles