gpt4 book ai didi

javascript - 如何在 JavaScript 中只触发一次函数

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:29:32 24 4
gpt4 key购买 nike

我正在构建一个星球大战搜索应用程序,其中有一个充满星球大战 Angular 色信息的对象,您可以使用匹配的 map 函数动态搜索该对象将其转换为在用户搜索字符时触发的正则表达式。

一切正常,但我添加了用户点击 Angular 色的功能(例如 Luke Skywalker),然后这会将 HTML 附加到 View 并添加有关 Luke< 的信息/强>。我正在努力让这个功能只触发一次,用户可以多次点击 Angular 色,它会继续添加相同的内容。

我怎样才能只允许用户点击 <li>一旦函数displayInfo()将触发一次。

感谢您的帮助。

var newView = document.querySelector(".starwars");

function displayInfo() {

newView.innerHTML += `
<div class="jedi">
<div class="image-wrapper">
<img id="swImage"src="img"
class="thumb reserved-ratio" alt="Luke Skywalker">
</div>
<div class="desc-sizer">
<p class="desc">Luke Skywalker was a Tatooine farmboy who rose from humble beginnings to become one of the greatest Jedi the galaxy
has ever known.
</p>
</div>
</div>
`;
searchInput.value = 'Luke Skywalker';
searchInput.addEventListener("focus", displayMatches);
searchInput.focus();
}

最佳答案

EventTarget.addEventListener() Parameters :

选项:可选

once: A Boolean indicating that the listener should be invoked at most once after being added. If true, the listener would be automatically removed when invoked.

您可以将 { once: true } 作为第三个参数传递给 addEventListener():

searchInput.addEventListener("focus", displayMatches, { once: true });

演示:

function displayInfo() {
var searchInput = document.querySelector('.searchInput');
searchInput.value = 'Luke Skywalker';
searchInput.addEventListener("focus", displayMatches, {once: true});
searchInput.focus();
}
displayInfo();
function displayMatches(){
alert('This function will be invoked only once!!!');
}
<input class="searchInput" />

关于javascript - 如何在 JavaScript 中只触发一次函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53930586/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com