javascript 如何检查“this”是否具有特定属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5487504/
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
How to check if 'this' has a specific attribute?
提问by iWebaholic
I want to check if the element I click (this) has a specific attribute, as a condition in the if clause. Is it possible to do this with JavaScript or jQuery?
我想检查我单击的元素(this)是否具有特定属性,作为 if 子句中的条件。是否可以使用 JavaScript 或 jQuery 来做到这一点?
Thanks
谢谢
回答by jessegavin
I will give the non-jQuery answer, just for kicks and giggles.
我会给出非 jQuery 的答案,只是为了逗笑。
this.hasAttribute("foo")
Documentation: https://developer.mozilla.org/en/DOM/element.hasAttribute
文档:https: //developer.mozilla.org/en/DOM/element.hasAttribute
回答by Andrew Hare
In JavaScript, anything that is null
or undefined
(or even an empty string) is implicitly "false" so you can do this (assuming that you were referring to a HTML attribute using jQuery):
在 JavaScript 中,任何是null
或undefined
(甚至是空字符串)的东西都隐式为“false”,因此您可以这样做(假设您使用 jQuery 引用 HTML 属性):
if ($(this).attr('foo')) {
}
Also, if you need the value from the attribute you can do this:
此外,如果您需要属性中的值,您可以执行以下操作:
var foo;
if (foo = $(this).attr('foo')) {
// use "foo" in here
}
回答by Christopher Armstrong
You mean something like this?\
你的意思是这样的?\
if ($.trim($(this).attr('attribute')) != '')
{ ... }
回答by RobG
If you are after an HTML attribute, then getAttribute is the only reasonably reliable way to go, noting that it has quirks in IE.
如果您在寻找 HTML 属性,那么 getAttribute 是唯一合理可靠的方法,请注意它在 IE 中存在一些怪癖。
If you are just after a DOM property, then simply:
如果您只是在追求 DOM 属性,那么只需:
if (this.foo) {
...
}
will probably do. The test returns false if foo is set to the number zero (0), empty string, null, NaN or undefined. So it doesn't actually tell you if the element has that property, only that attempting to access it returns a falsey value. But that is usually sufficient.
可能会做。如果 foo 设置为数字零 (0)、空字符串、null、NaN 或未定义,则测试返回 false。所以它实际上并没有告诉您元素是否具有该属性,只是尝试访问它会返回一个 falsey 值。但这通常就足够了。