我尝试删除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); }
}
function 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>
答案 0 :(得分:0)
看起来你的投票[i]应该是投票[index]
但你也可以先检查一下remove事件监听器是否是一个函数
if(vote[index].removeEventListener == "function") {
// you can remove it
} else { // you can't remove it, it doesn't have a listener
}