首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法通过EventListener删除removeEventListener

无法通过EventListener删除removeEventListener
EN

Stack Overflow用户
提问于 2014-12-24 15:26:20
回答 1查看 6.6K关注 0票数 0

我正在尝试删除EventListener,但是在Chrome调试模式下显示的错误消息如下:

未定义的TypeError:无法读取未定义的属性“removeEventListener”

我不知道问题出在哪里,密码如下:

代码语言:javascript
复制
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() {

代码语言:javascript
复制
        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>

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-12-24 15:38:55

看来你的投票应该是投票索引

但是,您也可以先检查删除事件侦听器是否是一个函数。

代码语言:javascript
复制
if(typeof vote[index].removeEventListener === "function") {
  // you can remove it 
} else { // you can't remove it, it doesn't have a listener
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27639077

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档