jQuery查找输入类型(也用于选择) [英] jQuery find input type (but also for select)
问题描述
我需要找到单选按钮,文本和选择的输入类型.使用<input type="x">
可以轻松找到任何输入类型,因为$(this).attr("type")
会返回x
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
我的问题是我需要支持<select>
元素,这些元素没有type属性.最终目标是返回单选,文本或选择.
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.
我想做这样的事情,但是我很好奇是否有更好的方法:
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)
}
谢谢!
推荐答案
您可以执行此操作(在这里拨弄),制作一些易于使用的插件:
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(); }
并像这样使用它
$(".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.
其他信息
如果您只想拥有一些选择器,则可以使用以下方法:
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
这篇关于jQuery查找输入类型(也用于选择)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!