Javascript event handler scope

This is probably a simple question, but I can’t find a better answer for him.

I have 10 <div>elements on the screen. Each of them has an event listener click():

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
    <div id="element0">Click me! (0)</div>
    <div id="element1">Click me! (1)</div>
    <div id="element2">Click me! (2)</div>
    <div id="element3">Click me! (3)</div>
    <div id="element4">Click me! (4)</div>
    <div id="element5">Click me! (5)</div>
    <div id="element6">Click me! (6)</div>
    <div id="element7">Click me! (7)</div>
    <div id="element8">Click me! (8)</div>
    <div id="element9">Click me! (9)</div>
    <script type="text/javascript">
    for ( var i = 0; i < 10; i++ ) {
        var element = document.getElementById( "element" + i );
        element.onclick = function () {
            alert( "Element " + i );
        }
    }
    </script>
</body>
</html>

But every time I click on an element, it says "Element 10"! It seems that all of these event handlers use the same value for i.

I want it to show "Element N", where N is the number of the current element. I do not want to extract N from the identifier of the element. I also do not want to store it using data()jQuery method . I believe that the solution to this problem should be much simpler, but I can not find it. Is anyone

+3
source share
3 answers

i , . i . :

for ( var i = 0; i < 10; i++ ) {
    var element = document.getElementById( "element" + i );
    element.onclick = (function(i){
        // returns a new function to be used as an onclick handler
        return function () {
            alert( "Element " + i );
        }
    })(i); // Pass in the value of the outer scope i
}

" " ( ) :)

+6

, , , . , .

document.body.onclick = function(e) {
  if (e.target.tagName.toLowerCase() === "div") {
    alert( "Element " + e.target.id );
  }
}

jQuery, :

$(document.body).on("click", "div", function() {
  alert($(this).attr("id"));
});

: http://www.sitepoint.com/javascript-event-delegation-is-easier-than-you-think/

, jQuery libs .

+2

You can capture the number from the attribute id:

for ( var i = 0; i < 10; i++ ) {
    var element = document.getElementById( "element" + i );
    element.onclick = function () {

        var i = this.id.substr(7);
        alert( "Element " + i );
    }
}​

JsFiddle is here .

+1
source

All Articles