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
source
share