我想检查一下DOM元素的特定属性是否未定义 - 我该怎么做?
我试过这样的事情:
if (marcamillion == undefined) {
console.log("Marcamillion is an undefined variable.");
}
ReferenceError: marcamillion is not defined
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,引用错误告诉我该变量未定义,但我的if检查显然不起作用,因为它生成标准js ReferenceError而不是我正在寻找的错误消息console.log.
编辑1
或者更好的是,如果我试图确定元素的属性是否未定义如下:
$(this).attr('value')
什么是确定是否未定义的最佳方法?
rom*_*ger 18
使用typeof:
if (typeof marcamillion == 'undefined') {
console.log("Marcamillion is an undefined variable.");
}
Run Code Online (Sandbox Code Playgroud)
编辑第二个问题:
if ($(this).attr('value')) {
// code
}
else {
console.log('nope.')
}
Run Code Online (Sandbox Code Playgroud)
if (typeof marcamillion === 'undefined') {
console.log("Marcamillion is an undefined variable.");
}
Run Code Online (Sandbox Code Playgroud)
请注意,使用===而不是==被认为是更好的风格.
| 归档时间: |
|
| 查看次数: |
38405 次 |
| 最近记录: |