如何知道 jQuery 对象的类型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1864151/
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 know the type of an jQuery object?
提问by user198729
I need to detect whether it's a <option>
or something else
我需要检测它是一个<option>
还是别的什么
回答by Andrew Hare
Try this:
尝试这个:
yourObject[0].tagName;
Since a jQuery object is an array of objects you can retrieve the underlying DOM element by indexing that array. Once you have the element you can retrieve its tagName
. (Note that even if you have one element you will still have an array, albeit an array of one element).
由于 jQuery 对象是一个对象数组,因此您可以通过索引该数组来检索底层 DOM 元素。一旦你有了元素,你就可以检索它的tagName
. (请注意,即使您有一个元素,您仍然会有一个数组,尽管是一个包含一个元素的数组)。
回答by SLaks
回答by gnarf
You should be able to check the .nodeName
property of the element. Something about like this should work for you:
您应该能够检查.nodeName
元素的属性。像这样的事情应该适合你:
// a very quick little helper function
$.fn.getNodeName = function() {
// returns the nodeName of the first matched element, or ""
return this[0] ? this[0].nodeName : "";
};
var $something = $(".something");
alert($something.getNodeName());
I generally prefer using jQuery's .is()
to test what something is.
我通常更喜欢使用 jQuery.is()
来测试什么是什么。
Checks the current selection against an expression and returns true, if at least one element of the selection fits the given expression.
根据表达式检查当前选择并返回 true,如果选择的至少一个元素适合给定的表达式。
if ($something.is("option")) {
// work with an option element
}