简体   繁体   中英

addEventListener isn't working properly

I want to move some elements between two div's. Everything works normal with onclick event, but when i swicth to addEventListener it lets me switch just a few times the elements.

Here is a previev http://jsfiddle.net/2u6nyxp4/1/ .

Can someone explain why is that ? Thank you.

HTML

<div id="one">
  <span>One</span>
  <span>Two</span>
</div>

<div id="two"><span>One</span></div>

JAVASCRIPT

var one = document.getElementById('one');
var two = document.getElementById('two');

var movetoOne = function () {
  one.appendChild(this);
  bindEvents (this,movetoTwo);
}

var movetoTwo = function () {
  two.appendChild(this);   
  bindEvents (this,movetoOne);
}

var bindEvents = function (childList, moveEvent) {
  childList.onclick = moveEvent;

}


for (i=0; i < one.children.length ; i+=1 ) {
  bindEvents(one.children[i], movetoTwo);   
}

for (i=0; i < two.children.length ; i+=1 ) {
    bindEvents(two.children[i], movetoOne);
}

If you use oncklick there is only one event-handler for the event at a time. Each time you call bindEvents the old one becomes overwritten by the new one.

If you use addEventListener , each time you call bindEvents a new handler is added to the existing. After ten clicks there are five handlers movetoOne and five movetoTwo attached to the same element and the browser is totally confused.

The way out: remove the existing handler before adding a new one like so:

var bindEvents = function (childList, moveEvent) {
    var old = movetoOne;
    if (old === moveEvent) old = movetoTwo;      
    childList.removeEventListener('click', old);
    childList.addEventListener('click', moveEvent);
}

Working DEMO here . - - - Reference: removeEventListener() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM