31

我需要找到单选按钮、文本和选择的输入类型。很容易找到任何东西的输入类型,<input type="x">因为$(this).attr("type")会返回x

我的问题是我需要支持<select>没有 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)
}

谢谢大家!

4

2 回答 2

70

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

$.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
于 2012-02-02T17:15:42.567 回答
7

所有类型的输入框和选择框通过 jQuery find 汇集在一起​​:

$('#myForm').find('select,input').each(function(i,box){
     alert($(box).attr('name'));
}
于 2018-10-08T07:41:17.040 回答