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

jQuery查找输入类型(但也适用于select),jquery,select,tagname,Jquery,Select,Tagname,我需要找到单选按钮、文本和选择的输入类型。很容易找到任何带有的输入类型,因为$(this).attr(“type”)将返回x 我的问题是我需要支持元素,这些元素没有type属性。最终目标是返回收音机、文本或选择 我曾想过这样做,但我很好奇是否有更好的方法: if ($(this).tagName == "input") { var result = $(this).attr("type"); //returns radio or text (the attr type) } else

我需要找到单选按钮、文本和选择的输入类型。很容易找到任何带有
的输入类型,因为
$(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");
或选择所有表单控件():


所有类型的输入框,并选择框通过jQuery聚集查找:

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