Javascript 整个表格 onChange
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10760847/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Entire form onChange
提问by Mori
How can I use onChange
or a similar event for all form
elements? I don't want to use onChange
for each field separately.
我如何onChange
为所有form
元素使用或类似的事件?我不想onChange
分别用于每个字段。
回答by Mori
You can use the change
event on the form
element:
您可以change
在form
元素上使用事件:
var form = document.querySelector('form');
form.addEventListener('change', function() {
alert('Hi!');
});
回答by Steve
If you are using jQuery, you can use the change
event on the form element, because in jQuery the event bubbles up.
如果您使用 jQuery,则可以change
在表单元素上使用该事件,因为在 jQuery 中,事件会冒泡。
$('#formId').change(function(){...});
If you are using plain javascript, the change event does not bubble (at least not cross browser). So you would have to attach the event handler to each input element separately:
如果您使用普通的 javascript,则更改事件不会冒泡(至少不会跨浏览器)。因此,您必须分别将事件处理程序附加到每个输入元素:
var inputs = document.getElementsByTagName("input");
for (i=0; i<inputs.length; i++){
inputs[i].onchange = changeHandler;
}
(of course, you would have to do a similar thing to all selects and textareas)
(当然,您必须对所有选择和文本区域做类似的事情)