【问题标题】:How do I check if an element is undefined? [duplicate]如何检查元素是否未定义? [复制]
【发布时间】:2013-03-16 01:00:45
【问题描述】:

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

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

【问题讨论】:

标签: javascript


【解决方案1】:

使用typeof:

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

编辑第二个问题:

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

【讨论】:

  • 假设我有一个属性,我正在尝试测试它的值 - 即$(this).attr('value')...确定它是否未定义的最佳方法是什么?
  • 只需执行if ($(this).attr('value')) 即可。
  • 如何检测not 版本?在 ruby​​ 中,我只需在条件前面添加一个!,但我现在收到一个错误......或者这不可能吗?
  • if (!$(this).attr('value')) 应该可以工作。你得到什么错误?
  • 奇怪...我之前遇到过错误。不太清楚为什么......但谢谢!
【解决方案2】:
if (typeof marcamillion === 'undefined') {
    console.log("Marcamillion is an undefined variable.");
}

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

【讨论】:

  • 假设我有一个属性,我正在尝试测试它的值 - 即$(this).attr('value')...确定它是否未定义的最佳方法是什么?
猜你喜欢
  • 2012-04-28
  • 2017-08-02
  • 2011-06-12
  • 2014-05-01
  • 2011-03-24
  • 2013-08-18
  • 2011-09-25
  • 2019-10-14
相关资源
最近更新 更多