我正在尝试删除EventListener,但是在Chrome调试模式下显示的错误消息如下:
未定义的TypeError:无法读取未定义的属性“removeEventListener”
我不知道问题出在哪里,密码如下:
window.addEventListener("load", init, false);
var vote = null;
function init() {
vote = document.querySelectorAll("div>span>img");
for (var index = 0; index < vote.length; index++) {
//document.getElementById(("img" + index)).innerHTML = '<img src="../images/voteoff.png" />';
event.stopPropagation();
vote[index].setAttribute("src", "../images/voteoff.png");
vote[index].setAttribute("id", index);
vote[index].addEventListener("mouseover", handleMouseOver, false);
vote[index].addEventListener("mouseout", handleMouseOut, false);
vote[index].addEventListener("click", MouseOnclickVote, false);
//vote[index].onmouseover = function () { MouseOverVote(this.id);}
//vote[index].onmouseout = MouseOutVote;
event.stopPropagation();
//vote[index].onclick = function () { MouseOnclickVote(this.id); }
}函数MouseOnclickVote() {
length = this.id;
console.debug(length);
for (var index = 0; index <= length ; index++) {
console.debug(index);
console.debug(vote[index]);
vote[index].removeEventListener("mouseout", handleMouseOver);
vote[index].removeEventListener("mouseover", handleMouseOut);
}
}
}
var handleMouseOver = function MouseOverVote() {
length = this.id;
for (var index = 0; index <= length ; index++) {
vote[index].setAttribute("src", "../images/voteok.png");
vote[index].parentNode.parentNode.nextSibling.nextSibling.firstChild.textContent = "你按了" + (index + 1) + "個讚";
event.stopPropagation();
}
}
var handleMouseOut = function MouseOutVote() {
for (var index = 0; index < vote.length ; index++) {
vote[index].setAttribute("src", "../images/voteoff.png");
vote[index].parentNode.parentNode.nextSibling.nextSibling.firstChild.textContent = "";
event.stopPropagation();
}
}
</script>
发布于 2014-12-24 15:38:55
看来你的投票应该是投票索引
但是,您也可以先检查删除事件侦听器是否是一个函数。
if(typeof vote[index].removeEventListener === "function") {
// you can remove it
} else { // you can't remove it, it doesn't have a listener
}https://stackoverflow.com/questions/27639077
复制相似问题