The following JavaScript has some unwanted behaviour:
<html>
<script>
function AddEventListener(el, listener)
{
el.addEventListener ? el.addEventListener('click', listener) :
el.attachEvent('onclick', listener);
}
function Init(parent)
{
var span = document.createElement("span");
span.innerText = "Span1";
AddEventListener(span, function() { alert(span.innerText); } );
parent.appendChild(span);
var span = document.createElement("span");
span.innerText = "Span2";
parent.appendChild(span);
}
</script>
<body onload="Init(document.getElementById('drop'));">
<div id='drop'></div>
</body>
</html>
If you click on Span1, Span2 is shown in the alert window. I understand why: javascript variable scope. But I don’t know how to solve it.
Some context: I used this.innerHTML which works fine except in IE8. this points to the window in IE8, not to the parent of the event listener.
Instead of using a global variable in your click callback, you can use the
eventparameter that is being passed to every event you register, and then use itsevent.targetparameter to get the DOM element that participated in the event.For that, you may change your event listener registering to:
AddEventListener(span,function(event) {alert((event.target ? event.target : event.srcElement).innerText);});I’ve set up an example of it using your code here: http://jsfiddle.net/dvirazulay/fTa6T/1/