无法读取菜单上 null 的属性“addEventListener" [英] Cannot read property 'addEventListener' of null on menu

查看:61
本文介绍了无法读取菜单上 null 的属性“addEventListener"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试实现响应式菜单.添加的脚本如下

Trying to implement a responsive menu. added script which is as follows

    (function() {

    var bodyEl = document.body,
        content = document.querySelector( '.content-wrap' ),
        openbtn = document.getElementById( 'open-button' ),
        closebtn = document.getElementById( 'close-button' ),
        isOpen = false;

    function init() {
        initEvents();
    }

    function initEvents() {
        openbtn.addEventListener( 'click', toggleMenu );
        if( closebtn ) {
            closebtn.addEventListener( 'click', toggleMenu );
        }

        // close the menu element if the target it´s not the menu element or one of its descendants..
        content.addEventListener( 'click', function(ev) {
            var target = ev.target;
            if( isOpen && target !== openbtn ) {
                toggleMenu();
            }
        } );
    }

    function toggleMenu() {
        if( isOpen ) {
            classie.remove( bodyEl, 'show-menu' );
        }
        else {
            classie.add( bodyEl, 'show-menu' );
        }
        isOpen = !isOpen;
    }

    init();
})();

并且标记包括必要的类和按钮.出于某种原因,我在 openbtn.addEventListener( 'click', toggleMenu ); 上得到了无法读取 null 的属性 'addEventListener'.Javascript 菜鸟,一直无法解决这个问题.

and the markup includes the neccessary classes and buttons. For some reason I am getting Cannot read property 'addEventListener' of null on the openbtn.addEventListener( 'click', toggleMenu );. Javascript rookie and haven't been able to solve this.

有什么建议吗?

推荐答案

很可能在脚本执行时元素不在 DOM 中.您需要在 DOM 初始化后调用 init 方法.

Most likely the element is not there in the DOM when the script is executing. You will need to call the init method after the DOM has initialized.

将脚本移到 body 标签之后的底部.或使用 jquery 并在 $(document).ready() 中调用您的 init 方法.

Move the script to the bottom after the body tag. or use jquery and call your init method inside $(document).ready().

另外,考虑将变量初始化移动到 init 方法中

Also, consider moving the variable initializations to the init method

    bodyEl = document.body,
    content = document.querySelector( '.content-wrap' ),
    openbtn = document.getElementById( 'open-button' ),
    closebtn = document.getElementById( 'close-button' )

以便他们在 dom 加载后读取正确的值,而不是在脚本初始化时读取.

so that they read the proper values after the dom is loaded, instead of when the script is initialized.

这篇关于无法读取菜单上 null 的属性“addEventListener"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆