简体   繁体   English

如何在 Elementor 中向弹出窗口添加单击事件?

[英]How can I add a click event to popup in Elementor?

Using WordPress and Elementor page builder I created a navmenu popup template.我使用 WordPress 和 Elementor 页面构建器创建了一个导航菜单弹出模板。 I want to fade-in submenu items and hide the menu when clicking a menu item that has a sub menu in it.我想在单击包含子菜单的菜单项时淡入子菜单项并隐藏菜单。

When I add JavaScript code to the popup (using add-ons), eventlistener function doesn't work, but my code works fine.当我将 JavaScript 代码添加到弹出窗口(使用附加组件)时,事件侦听器功能不起作用,但我的代码工作正常。 I use it in simple pages but not in the popup itself;我在简单的页面中使用它,但不在弹出窗口中使用它; I tried (custom CSS and JS) plugin it didn't work either.我尝试了(自定义 CSS 和 JS)插件,它也不起作用。 Is it a bug in Elementor or can't addevenlistener work for an element in the popup in the usual way?这是 Elementor 中的错误还是无法以通常的方式 addevenlistener 为弹出窗口中的元素工作?

Code :代码 :

const element = document.querySelector('.element');

console.log(element);  < ------------------------------here is working!!!

element.addEventListener('click', function(){
    any code in here <---------------------------------------not working !
});

I think the problem might be, that you are using querySelector .我认为问题可能是,您正在使用querySelector It returns the first Element within the document that matches the specified selector, or group of selectors.它返回文档中与指定选择器或选择器组匹配的第一个元素。

With wordpress, you are able to use jQuery instead of pure javascript.使用 wordpress,您可以使用 jQuery 而不是纯 javascript。 So you are able to use .click .所以你可以使用.click Might be worth a try using another way to achieve what you want:可能值得尝试使用另一种方式来实现您想要的:

( function( $ ) {
    $(document).ready(function () {
      $(".element").click(function (e) {
        e.preventDefault();
        // any code here
      });
    });
}( jQuery ) );

Here is some more information: https://api.jquery.com/click/以下是更多信息: https : //api.jquery.com/click/

But if you like to use pure javascript, you can use for every element like:但是,如果你喜欢用纯JavaScript,可以使用for像每一个元素:

window.onload = function () {
  element = document.querySelectorAll(".element");
  for (var i = 0; i < element.length; i++) {
    element[i].addEventListener("click", function (e) {
        e.preventDefault();
        // any code here
    });
  }
};

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

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