jQuery查找输入类型(但也适用于select)

我需要找到单选按钮,文本和选择的输入类型。 使用很容易找到任何输入类型,因为$(this).attr("type")将返回x

我的问题是我需要支持元素,它们没有type属性。 最终目标是返回收音机,文本或选择。

我想做这样的事情,但我很好奇,如果有更好的方法:

 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) } 

谢谢大家!

你可以这样做( 在这里小提琴 ),制作一些易于使用的插件:

 $.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 

这将获得所选第一个元素的类型。

其他信息

如果你只想要一些选择器,你可以使用它:

 $("input:text, input:radio, select"); 

或者选择所有表单控件( 更多信息 ):

 $(":input") // can return all form types 

所有类型的输入框和选择框通过jQuery聚集在一起找到:

 $('#myForm').find('select,input').each(function(i,box){ alert($(box).attr('name')); }