我想在函数完成后停止eventListener, 这是插图:
我做了一个图标,单击它会显示input form
,然后当我的光标clicked
或mouseover
再次在该输入下方显示button
搜索,但是当我再次单击并单击时,按钮搜索会继续在下面添加元素按钮
这是代码:
let FunFun = document.querySelector( "img#pic" ).addEventListener( "click", () => {
let newEl = document.createElement("input");
newEl.id = "inPut"
newEl.type = "text";
newEl.name = "foo";
newEl.value = "";
newEl.placeholder = "type your city";
let oldEl = document.querySelector("#pic")
//parentEL
let parentEl = document.querySelector( ".addCity" )
parentEl.replaceChild( newEl, oldEl )
let btN = document.querySelector( "#inPut" ).addEventListener( "click", () => {
btN = document.createElement( "button" )
btN.class = "btn0"
btN.textContent = "search"
let _input = document.querySelector("#inPut")
_input.after(btN)
// tried wrote code removeEventListener also, but nothing error and cant make the event stop
}) end the btN
// console.log(btN)
// let buttnRm = document.querySelector("#inPut").removeEventListener("click", () => { console.log("test" )});
}) // end the FunFun
我上面的代码在控制台上没有错误,我试图将removeEven侦听器放在函数btN
下,但出现了错误,就像上面的代码一样,
我试图在上面的函数中编写如下代码:
.addEventListener("click", myFunction, true) // false
.removeEventListener("click", myFunction, true) // false
我在上面切换了是非,但还是没事
在功能input
运行后,当我单击addeventlistener
表单元素时,按钮的一些图片越来越多
答案 0 :(得分:0)
首先,您必须声明一个函数eventHandler
作为您的事件侦听器,然后再使用removeEventListener
将其删除
let eventHandler = () => {
btN = document.createElement( "button" )
btN.class = "btn0"
btN.textContent = "search"
let cityInput = document.querySelector( "#inPut" )
cityInput.after(btN)
// Remove the eventListener just after the first call
cityInput.removeEventListener('click' , eventHandler, true)
}
选择输入元素并将其存储为变量。
let cityInput = document.querySelector( "#inPut" ); // select the input element
cityInput.addEventListener( "click", eventHandler, true) // add a non-anonymous function as event listener
let FunFun = document.querySelector( "img#pic" ).addEventListener( "click", () => {
let newEl = document.createElement("input");
newEl.id = "inPut"
newEl.type = "text";
newEl.name = "foo";
newEl.value = "";
newEl.placeholder = "type your city";
let oldEl = document.querySelector("#pic")
//parentEL
let parentEl = document.querySelector( ".addCity" )
parentEl.replaceChild( newEl, oldEl )
let eventHandler = () => {
btN = document.createElement( "button" )
btN.class = "btn0"
btN.textContent = "search"
cityInput.after(btN)
cityInput.removeEventListener('click' , eventHandler, true)
}
let cityInput = document.querySelector( "#inPut" );
cityInput.addEventListener( "click", eventHandler, true) // end the btN
// console.log(btN)
// let buttnRm = document.querySelector("#inPut").removeEventListener("click", () => { console.log("test" )});
}) // end the FunFun
#pic {
height: 100px;
width: 100px;
border: 1px solid;
}
<div class='addCity'>
<img src='something.jpg' id='pic'>
</div>