[英]How to get the type of an element. JavaScript / jQuery
Right, idiot moment coming up. 对,白痴的时刻到了。 I've done a search, but can't find the right solution.
我已经进行了搜索,但是找不到正确的解决方案。
I've got a jQuery selector selecting a class, maybe an ID, in fact it could be anything, this selector is fed into a function I'm programming. 我有一个jQuery选择器来选择一个类,也许是一个ID,实际上它可以是任何东西,这个选择器被输入到我正在编程的函数中。
I need to be able to figure out the type of each matched element, for example: 我需要能够弄清楚每个匹配元素的类型,例如:
<div class="target"></div>
Would return div, and 将返回div,并且
<input class="target" />
Would return input, simple right? 将返回输入,简单吗?
Well you'd have thought so, but I cannot seem to find the solution. 好吧,您曾经这么想,但是我似乎找不到解决方案。
Any help would be greatly appreciated :-) 任何帮助将不胜感激 :-)
You need to get the underlying DOM element and access the tagName
property. 您需要获取基础的DOM元素并访问
tagName
属性。 For example, 例如,
alert($("#target").get(0).tagName);
// -> DIV
Be aware that browsers will return the tag name in uppercase, so something like this would cause you a bit of grief: 请注意,浏览器将以大写形式返回标签名称,因此,这样会引起您一些麻烦:
if ($("#target").get(0).tagName == "div") { alert("DIV!"); }
$.fn.tagName = function() {
return this.get(0).tagName;
}
alert($('#testElement').tagName());
To explain a little bit more of why your original example didn't work, the each() method will always return the original jQuery object (unless the jQuery object itself was modified). 为了进一步说明您的原始示例为何无效的原因,each()方法将始终返回原始的jQuery对象(除非jQuery对象本身已被修改)。 To see what is happening in each with your code, here is some pseudocode that shows how the each() method works:
要查看每个代码中发生了什么,下面是一些伪代码,显示了each()方法的工作方式:
function each(action) {
for(var e in jQueryElements) {
action();
}
return jQueryObject;
}
This is not how each() really gets implemented (by a long shot probably), but it is to show that the return value of your action() function is ignored. 这不是each()真正实现的方式(可能很远),而是要显示action()函数的返回值被忽略。
try: 尝试:
$("yourelement").is("input")
or: 要么:
if ($(this).is('input:checkbox'))
etc.... where appropriate 等...在适当的地方
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.