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

The*_*olf 3 javascript function ecmascript-6

我正在构建一个星球大战搜索应用程序,其中我有一个充满星球大战角色信息的对象,您可以使用与其匹配的地图函数动态搜索对象,该正则表达式在用户搜索角色时触发.

这一切都很完美,但我添加了用户点击角色(例如Luke Skywalker)的功能,然后将HTML添加到视图中并添加有关Luke的信息.我很难让这个功能只触发一次,用户可以在角色上多次点击,它会继续添加相同的内容.

我怎样才能让用户点击<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();
}
Run Code Online (Sandbox Code Playgroud)

Mam*_*mun 6

EventTarget.addEventListener()参数:

选项: 可选

once:一个布尔值,指示在添加后最多应调用一次侦听器.如果true,则在调用时将自动删除侦听器.

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

searchInput.addEventListener("focus", displayMatches, { once: true });
Run Code Online (Sandbox Code Playgroud)

演示:

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!!!');
}
Run Code Online (Sandbox Code Playgroud)
<input class="searchInput" />
Run Code Online (Sandbox Code Playgroud)