16

我想检查 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')

确定是否未定义的最佳方法是什么?

4

2 回答 2

26

使用typeof

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

编辑第二个问题:

if ($(this).attr('value')) {
    // code
}
else {
    console.log('nope.')
}
于 2013-03-26T09:35:27.747 回答
7
if (typeof marcamillion === 'undefined') {
    console.log("Marcamillion is an undefined variable.");
}

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

于 2013-03-26T09:37:18.360 回答