javascript 如何检查元素是否未定义?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15633576/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 01:28:09  来源:igfitidea点击:

How do I check if an element is undefined?

javascript

提问by marcamillion

I would like to check to see if a particular attribute of a DOM element is undefined - how do I do that?

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

I tried something like this:

我试过这样的事情:

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

As you can see, the reference error is telling me that the variable is not defined, but my ifcheck is clearly not working, because it is producing the standard js ReferenceErroras opposed to the error message I am looking for in my console.log.

如您所见,参考错误告诉我该变量未定义,但我的if检查显然不起作用,因为它生成的是标准 js ReferenceError,而不是我在console.log.

Edit 1

编辑 1

Or better yet, if I am trying to determine if the attribute of an element is undefined like this:

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

$(this).attr('value')

$(this).attr('value')

What would be the best way to determine if that is undefined?

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

回答by romainberger

Using typeof:

使用typeof

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

Edit for the second question:

编辑第二个问题:

if ($(this).attr('value')) {
    // code
}
else {
    console.log('nope.')
}

回答by Fabien

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

Note that using ===instead of ==is considered better style.

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