getElementById返回元素,但然后返回null

时间:2019-09-18 15:35:25

标签: javascript getelementbyid

所以我试图在我的JS中设置一些DOM元素的引用。但是,由于某种原因,它们返回正确的元素,但之后不久返回null。因此,我尝试将它们包装在if检查中,以确保元素不为null以防止这种情况。但是,它似乎仍在发生。

resizer.js

// Define DOM elements
const resizer = document.getElementById('resizer');
let btnMob;
let btnTablet;
let btnLaptop;
let btnDesktop;

// Check buttons exist and asign to variables if they do
if (document.getElementById('resizer-mob') !== null) {
    btnMob = document.getElementById('resizer-mob');
}
if (document.getElementById('resizer-tablet') !== null) {
    btnTablet = document.getElementById('resizer-tablet');
}
if (document.getElementById('resizer-laptop') !== null) {
    btnLaptop = document.getElementById('resizer-laptop');
}
if (document.getElementById('resizer-desktop') !== null) {
    btnDesktop = document.getElementById('resizer-desktop');
}

// Define string constants
const DESKTOP_CLASS = 'resizer--desktop';
const LAPTOP_CLASS = 'resizer--laptop';
const TABLET_CLASS = 'resizer--tablet';
const MOB_CLASS = 'resizer--mob';

// Check elements have been asign correctly
console.log('mob is ', btnMob);
console.log('tablet is ', btnTablet);
console.log('laptop is ', btnLaptop);
console.log('desktop is ', btnDesktop);


// Update resizer to display desktop
btnDesktop.addEventListener('click', () => {
    console.log("DESKTOP");
    resizer.classList.remove(LAPTOP_CLASS);
    resizer.classList.remove(TABLET_CLASS);
    resizer.classList.remove(MOB_CLASS);

    resizer.classList.add(DESKTOP_CLASS);
});

// Update resizer to display laptop
btnLaptop.addEventListener('click', () => {
    console.log("LAPTOP");
    resizer.classList.remove(DESKTOP_CLASS);
    resizer.classList.remove(TABLET_CLASS);
    resizer.classList.remove(MOB_CLASS);

    resizer.classList.add(LAPTOP_CLASS);
});

// Update resizer to display tablet
btnTablet.addEventListener('click', () => {
    console.log("TABLET");
    resizer.classList.remove(DESKTOP_CLASS);
    resizer.classList.remove(LAPTOP_CLASS);
    resizer.classList.remove(MOB_CLASS);

    resizer.classList.add(TABLET_CLASS);
});

// Update resizer to display mobile
btnMob.addEventListener('click', () => {
    console.log("MOB");
    resizer.classList.remove(DESKTOP_CLASS);
    resizer.classList.remove(LAPTOP_CLASS);
    resizer.classList.remove(TABLET_CLASS);

    resizer.classList.add(MOB_CLASS);
});

2 个答案:

答案 0 :(得分:0)

您尝试过!=而不是!==吗? 并返回null或未定义?

如果未定义,则需要使用:

typeof(element) != 'undefined'

答案 1 :(得分:0)

该代码的行为符合预期。首次运行代码时,所有操作均正常,因为您尚未删除任何元素。第二次使用,因此某些元素返回null,因为它们不再存在。