简体   繁体   English

Vanilla JS 相当于 jQuery $.once()?

[英]Vanilla JS equivalent to jQuery $.once()?

Working on a Drupal 9 site and trying to add some custom JS code to a page.在 Drupal 9 站点上工作并尝试向页面添加一些自定义 JS 代码。

Drupal.behaviors.syfyGlobalHideMenu = {
  attach: function (context, settings) {
    $('.nav-flyout', context).once('remove-modals', function () {
      $(document).keyup(function (e) {
        if (e.keyCode == 27) {
          $('.nav-flyout', context).removeClass('js-flyout-active');
        }
      });
    });
  }
};

Wondering if there's a vanilla JS equivalent to the jQuery.once functionality above?想知道是否有与上面的 jQuery.once 功能等效的香草 JS? Currently Drupal attaches the event listener multiple times and I am trying to avoid that as I only want to attach the event listener once but have it remain attached and run every time the event is invoked.目前 Drupal 多次附加事件侦听器,我试图避免这种情况,因为我只想附加一次事件侦听器,但每次调用事件时都保持附加并运行。

let intervalID = null;
const search = document.querySelector(".call-us-table input#edit-search");

search.addEventListener("keydown", event => {
  form.setAttribute("onsubmit", "return false");
  clearInterval(intervalID);
});
search.addEventListener("keyup", event => {
  intervalID = setInterval(submitForm, 2000);
});

Jquery once adds an html attribute to check if is the first time to run. Jquery 一次添加一个 html 属性来检查是否是第一次运行。

function vanillaOnce() {
  if (!document.body.getAttribute('data-once')) {
    document.body.setAttribute('data-once', 'true');
    return true;
  } else {
    return false;
  }
}

if (vanillaOnce) {
  console.log('runs only once');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM