简体   繁体   English

如何使用 jQuery 添加事件侦听器?

[英]How to add event listener using jQuery?

Have this code and tried to hide my side navbar when clicked outside the #nav , got this error.拥有此代码并尝试在#nav外部单击时隐藏我的侧面navbar ,出现此错误。

Cannot read property 'addEventListener' of null无法读取 null 的属性“addEventListener”

$( document ).ready( function() {
    setTimeout(function(){
        $('.menu-opener').click(function(){
            $('#nav').toggleClass('active');
        });
        let slide = document.querySelector('#nav .active');
        slide.addEventListener('click', function(e) {
            if (e.target !== slide) return;
            $('#nav').removeClass('active'); 
        });
    }, 1000);
}); 

answer is that you need to detect click outside of div you are trying to hide:答案是您需要检测要隐藏的 div 之外的点击:

$(window).click(function() {
//Hide the menus if visible
});

//stopping above function from  running when clicking on #nav itself
$('#nav').click(function(event){
    event.stopPropagation();
});

Try this inside setTimeout在 setTimeout 中试试这个

$('body').on('click','#nav .active', function(e){
   // your logic
})

OR或者

$( "'#nav .active'" ).bind( "click", function(e) {
// your logic
});

instead of代替

let slide = document.querySelector('#nav .active');
        slide.addEventListener('click', function(e) {
            if (e.target !== slide) return;
            $('#nav').removeClass('active'); 
        });

Got this working with得到了这个

$(document).click(function(event) { 
    if(!$(event.target).closest('#nav').length && !$(event.target).closest(".menu-opener").length)
    {
        $('#nav').removeClass('active');
    }        
});

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

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