我想从 2 个不同的元素模式中找到一些变量。
var something = $('.class').attr('data-something');
if(typeof something === 'undefined') {
var something = $('.class').attr('data-another');
}
if(typeof something != 'undefined') {
// do action...
console.log(something);
}
我只想从 attr 获取一些数据 data-someting="mydata"
如果找不到data-someting="mydata"
,则查找数据表单data-another
然后采取行动......
我做得对吗?或者另一种正确的方法可以做得更好?
Try Catch
怎么样?
最佳答案
有些浏览器会未定义
,而有些浏览器会返回false
。因此,这是一个更强大的版本:
if (typeof something === 'undefined' || something === false) {
// try another attribute
} else {
// do your stuff
}
更新:
嗯,根据the doc :
As of jQuery 1.6, the .attr() method returns
undefined
for attributes that have not been set.
因此,从 1.6 开始,他们可能会明确地确保这一点,而我关于 false
的信息已经过时了。在这种情况下,您自己的代码是完全正确的。
关于javascript - 使用 2 种情况查找某些变量的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16853310/