[英]Alternative way to undo an addEventListener without removeEventListener?
I just got started with JS and having hard time to deal with eventListeners...我刚开始使用 JS,很难处理 eventListeners ......
I am trying to find a way to re-hide some HTML elements on my page after the user re-clicks on them again.在用户再次单击它们后,我试图找到一种方法来重新隐藏我的页面上的一些 HTML 元素。
So far, the only way that I know to undo an Event which was triggered by using addEventListener is by assigning the same function to the same event (function removeEventListener), however, in the code below,it does not matter whether I try to use an anonymous function or if I reuse the same function and only change the "block" attribute back to "none";到目前为止,我知道撤消使用 addEventListener 触发的事件的唯一方法是将相同的 function 分配给相同的事件(函数 removeEventListener),但是,在下面的代码中,我是否尝试使用都没有关系匿名 function 或者如果我重用相同的 function 并且仅将“块”属性更改回“无”; It won't work.它行不通。
Any suggestions?有什么建议么?
Thank you in advance.先感谢您。
let snake = document.getElementById("snake");
let space = document.getElementById("space");
let fortune = document.getElementById("fortune");
//elements to be changed
let figure1 = document.getElementById("figure1");
let figure2 = document.getElementById("figure2");
let figure3 = document.getElementById("figure3");
//functions
function addFigure1(){
figure1.style.display="block";
};
function addFigure2(){
figure2.style.display="block";
};
function addFigure3(){
figure3.style.display="block";
};
///////////////////////////////////////////////////////
snake.addEventListener("click",addFigure1);
space.addEventListener("click",addFigure2);
fortune.addEventListener("click",addFigure3);
You can set an attribute on the element which is the target of the event, thus saving the "state" of it您可以在作为事件目标的元素上设置一个属性,从而保存它的“状态”
function addFigure1(){
var display = figure1.getAttribute("display") || "block";
figure1.style.display=display;
display = display == "block" ? "none" : "block";
figure1.setAttribute("display", display);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.