Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

javascript - 只能调用一次的函数(A function that can only be called once)

So I've run into an issue where an image will be created over and over again if I keep focusing out of the textbox, I just want the picture to be created one time and if I decide to click in the textbox and focus away from it, I don't want more images to be created so just a one and done type of function.(因此,我遇到了一个问题,如果我不断将焦点移出文本框,则会一遍又一遍地创建图像,我只想一次创建图片,并且如果我决定单击文本框并把焦点从它,我不想创建更多的图像,所以只需要一个完成的功能即可。)

I tried experimenting with remove EventListener but that didn't really do anything for me.(我尝试使用remove EventListener进行实验,但这并没有为我做任何事情。) function validateData(validationType) { var alpha = /^[A-Za-z]+$/; if (validationType === "firstname") { var firstName = document.getElementsByName("firstname")[0]; if (firstName.value.match(alpha)) { alert("Yes"); } else { alert("No"); image(); } } } window.onload = function creator() { document.getElementsByName("firstname")[0].addEventListener('blur', () => validateData("firstname")); } function image() { var imgx = document.createElement("img"); imgx.src = "https://i.imgur.com/pwLBEus.jpg"; document.getElementById("imgsauce").appendChild(imgx); document.getElementsByName("firstname")[0].addEventListener('blur', image); document.getElementsByName("firstname")[0].removeEventListener('blur', image); } <h2>The Element</h2> <input type="text" name="firstname" class="input"> <div id="imgsauce"></div>   ask by EIRIKDAAE translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use the once option of EventTarget.addEventListener() :(使用EventTarget.addEventListener()once选项:)

document.getElementsByName("firstname")[0].addEventListener('blur', image, { once: true }); function image() { console.log('once'); var imgx = document.createElement("img"); imgx.src = "https://i.imgur.com/pwLBEus.jpg"; document.getElementById("imgsauce").appendChild(imgx); } <h2>The Element</h2> <input type="text" name="firstname" class="input"> <div id="imgsauce"></div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...