你如何处理jQuery中的表单更改? [英] How do you handle a form change in jQuery?
问题描述
在jQuery中,有没有一种简单的方法可以测试表单的元素是否有任何变化?
In jQuery, is there a simple way to test if ANY of a form's elements have changed?
编辑:我应该添加我只需要查看 click()
事件。
I should have added that I only need to check on a click()
event.
编辑:对不起,我真的应该更具体!假设我有一个表单,并且我有一个包含以下内容的按钮:
Sorry I really should have been more specific! Say I have a form and I have a button with the following:
$('#mybutton').click(function() {
// Here is where is need to test
if(/* FORM has changed */) {
// Do something
}
});
我如何测试表格自加载以来是否有变化?
How would I test if the form has changed since it was loaded?
推荐答案
你可以这样做:
$("form :input").change(function() {
$(this).closest('form').data('changed', true);
});
$('#mybutton').click(function() {
if($(this).closest('form').data('changed')) {
//do something
}
});
这为输入安装更改
事件处理程序在表单中,如果其中任何一个更改,则使用 .data()
将已更改的
值设置为 true
,然后我们只需检查点击该值,这假设 #mybutton
在表单内(如果不只是替换 $(this).closest('form')
使用 $('#myForm')
),但你可以使它更通用,如下所示:
This rigs a change
event handler to inputs in the form, if any of them change it uses .data()
to set a changed
value to true
, then we just check for that value on the click, this assumes that #mybutton
is inside the form (if not just replace $(this).closest('form')
with $('#myForm')
), but you could make it even more generic, like this:
$('.checkChangedbutton').click(function() {
if($(this).closest('form').data('changed')) {
//do something
}
});
参考资料:已更新
根据jQuery,这是一个选择所有表单控件的过滤器。
According to jQuery this is a filter to select all form controls.
http://api.jquery.com/input-selector/
:输入选择器基本上选择所有表单控件。
The :input selector basically selects all form controls.
这篇关于你如何处理jQuery中的表单更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!