2012年3月更新。
所以,在我最初回答这个问题的两年后,我回头看看,它已经变成了一个大混乱。我觉得是时候回到这个问题上来,让我的答案真正正确了,因为它得到了最多的好评和接受。
For the record, Titi's answer is wrong as it is not what the original poster asked for - it is correct that it is possible to reset a form using the native reset() method, but this question is trying to clear a form off of remembered values that would remain in the form if you reset it this way. This is why a "manual" reset is needed. I assume most people ended up in this question from a Google search and are truly looking for the reset() method, but it does not work for the specific case the OP is talking about.
我最初的回答是这样的:
// not correct, use answer below
$(':input','#myform')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
这可能适用于许多情况,包括OP,但正如评论和其他回答中指出的那样,将从任何值属性中清除单选/复选框元素。
一个更正确(但不完美)的答案是:
function resetForm($form) {
$form.find('input:text, input:password, input:file, select, textarea').val('');
$form.find('input:radio, input:checkbox')
.removeAttr('checked').removeAttr('selected');
}
// to call, use:
resetForm($('#myform')); // by id, recommended
resetForm($('form[name=myName]')); // by name
jQuery认为,单独使用:text、:radio等选择器是一种糟糕的做法,因为它们最终会求值为*:text,这会花费比正常情况下更长的时间。我确实更喜欢白名单的方法,希望我在最初的回答中使用了它。无论如何,通过指定选择器的输入部分,加上表单元素的缓存,这应该使它成为这里性能最好的答案。
如果人们默认的选择元素不是一个空值的选项,那么这个答案可能仍然有一些缺陷,但它肯定是通用的,这将需要根据具体情况进行处理。