确定jQuery中的输入类型
我正在所有表单元素上运行.each()循环。我无法找到确定输入类型的方法(无论是复选框,文本,选择,textarea等)。确定jQuery中的输入类型
任何想法?
// When submitting
$("input[name='event_form_submit']").click(function() {
$("form[name='tepg_form_processor'] :input").each(function() {
console.log($(this).attr("type"));
// Determine whether this is a select, input etc?
});
return false;
});
$("form[name='test'] :input").each(function() {
alert(this.type);
});
那么'select'和'textarea'没有'type'属性呢? –
运行小提琴,看到神奇:) –
这似乎工作,但我不知道为什么。 –
$("form[name='test'] :input").each(function() {
if(this.tagName == "INPUT") {
console.log(this.tagName + ": " + this.type);
}
else
console.log(this.tagName);
});
我会1)通过直接访问'this.tagName'替换'$(this).prop(“tagName”)'2)[删除任何链接到w3schools](http://w3fools.com/)。 –
我建议:
$("form[name='test'] :input").each(function() {
/* gets the type of the element ('checkbox','text','radio', etc
if there's no 'type' then it retrieves the tagName of the
element instead 'select','textarea', etc */
var inputType = this.type || this.tagName.toLowerCase();
console.log(inputType);
/* then does uses a switch to do something depending
on what you want to do */
switch (inputType) {
case 'text':
// do something with text-inputs
break;
case 'radio':
// do something with radio-inputs
break;
case 'select':
// do something with select-elements
break;
// ...etc...
default:
// do something with other elements, element-types
break;
}
});
什么'$(本).attr( “类型”)'返回?这应该没问题。你也可以简化为'this.type'。 –
如果你没有得到你所期望的,那么确保你选择了正确的东西 - 无论是为你的点击处理程序还是你正在循环的输入。如果是的话,获取类型值应该可以工作。 – 2013-02-04 10:08:09
@James'$(this).attr(“type”)''对'select','textarea'和'button'不起作用 –