为什么getElementById返回null

为什么getElementById返回null

本文介绍了为什么getElementById返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我按下图像时,我想向另一个HTML元素添加一个类。



HTML:

 < img src = images / hamburger_menu.svg alt =汉堡菜单 class = header__hamburger id =汉堡菜单> 

JAVASCRIPT:

  var navigation_bar = document.getElementById('nav'); 
var isChecked = false;
var hamburger = document.getElementById( hamburger-menu);

hamburger.addEventListener( click,function(){
if(!isChecked){
navigation_bar.classList.add( show);
}
});

在Firefox上,我收到TypeError:将addEventListener添加到元素时,汉堡包为null。

解决方案

您必须在创建元素后添加事件侦听器。因此,使用 window.onload



  window.onload = function(){var navigation_bar = document.getElementById('nav'); var isChecked = false; var hamburger = document.getElementById( hamburger-menu); hamburger.addEventListener( click,function(){if(!isChecked){navigation_bar.classList.add( show); console.log( ok)}}));}  
 < img src = images / hamburger_menu.svg alt =汉堡菜单 class =  header__hamburger id = hamburger-menu>< div id ='nav'> nav< / div>  


When I press on an image I want to add a class to another HTML element.

HTML :

<img src="images/hamburger_menu.svg" alt="Hamburger menu" class="header__hamburger" id="hamburger-menu">

JAVASCRIPT :

var navigation_bar = document.getElementById('nav');
var isChecked = false;
var hamburger = document.getElementById("hamburger-menu");

hamburger.addEventListener("click", function(){
    if(!isChecked){
        navigation_bar.classList.add("show");
    }
});

On Firefox I get TypeError: hamburger is null when I add addEventListener to the element. Any suggestions?

解决方案

You have to add the event listener after the element is created. So, use window.onload :

window.onload = function(){
    var navigation_bar = document.getElementById('nav');
    var isChecked = false;
    var hamburger = document.getElementById("hamburger-menu");

    hamburger.addEventListener("click", function(){
        if(!isChecked){
            navigation_bar.classList.add("show");
            console.log("ok")
        }
    });
}
<img src="images/hamburger_menu.svg" alt="Hamburger menu" class="header__hamburger" id="hamburger-menu">
<div id = 'nav'>nav</div>

这篇关于为什么getElementById返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 14:58