jQuery 查找输入类型(也适用于选择)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9116694/
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
jQuery find input type (but also for select)
提问by jaredrada
I need to find the input type for radio buttons, text, and selects. Its easy to find the input type of anything with <input type="x">
since $(this).attr("type")
would return x
我需要找到单选按钮、文本和选择的输入类型。很容易找到任何东西的输入类型,<input type="x">
因为$(this).attr("type")
会返回x
My issue is that I need to support <select>
elements, which dont have the type attribute. The end goal is to do return either radio, text, or select.
我的问题是我需要支持<select>
没有 type 属性的元素。最终目标是返回单选、文本或选择。
I thought of doing something like this, but I was curious if there's a better way:
我想做这样的事情,但我很好奇是否有更好的方法:
if ($(this).tagName == "input") {
var result = $(this).attr("type"); //returns radio or text (the attr type)
} else {
var result = $(this).tagName; //returns select (the element type)
}
Thanks all!
谢谢大家!
回答by Niels
You can do this (fiddle here), make some sort of easy to use plugin:
你可以这样做(在这里小提琴),制作某种易于使用的插件:
$.fn.getType = function(){ return this[0].tagName == "INPUT" ? this[0].type.toLowerCase() : this[0].tagName.toLowerCase(); }
And use it like this
并像这样使用它
$(".element").getType(); // Will return radio, text, checkbox, select, textarea, etc (also DIV, SPAN, all element types)
$(".elList").getType(); // Gets the first element's type
Which will get the type of the first element which is selected.
这将获得被选择的第一个元素的类型。
Other info
其他信息
If you just want to have some selectors you can use this:
如果你只想有一些选择器,你可以使用这个:
$("input:text, input:radio, select");
Or select all form controls (more info):
或选择所有表单控件(更多信息):
$(":input") // can return all form types
回答by Hasib Kamal
All types of input box and select box getting together by jQuery find :
jQuery 查找所有类型的输入框和选择框:
$('#myForm').find('select,input').each(function(i,box){
alert($(box).attr('name'));
}