如何检查元素是否未定义

How do I check if an element is undefined?

本文关键字:元素 是否 未定义 检查 何检查      更新时间:2023-09-26

我想检查一下DOM元素的特定属性是否未定义-我该怎么做?

我试过这样的东西:

if (marcamillion == undefined) {
    console.log("Marcamillion is an undefined variable.");
}
ReferenceError: marcamillion is not defined

正如您所看到的,引用错误告诉我变量尚未定义,但我的if检查显然不起作用,因为它正在生成标准的js ReferenceError,而不是我在console.log中查找的错误消息。

编辑1

或者更好的是,如果我试图确定一个元素的属性是否像这样未定义:

$(this).attr('value')

如果没有定义,最好的方法是什么?

使用typeof:

if (typeof marcamillion == 'undefined') {
    console.log("Marcamillion is an undefined variable.");
}

编辑第二个问题:

if ($(this).attr('value')) {
    // code
}
else {
    console.log('nope.')
}
if (typeof marcamillion === 'undefined') {
    console.log("Marcamillion is an undefined variable.");
}

请注意,使用===而不是==被认为是更好的样式。