在 jQuery 中,是否有一种简单的方法来测试表单的任何元素是否已更改?
假设我有一个表单和一个带有以下 click()
事件的按钮:
$('#mybutton').click(function() {
// Here is where is need to test
if(/* FORM has changed */) {
// Do something
}
});
我如何测试表单加载后是否发生了变化?
最佳答案
你可以这样做:
$("form :input").change(function() {
$(this).closest('form').data('changed', true);
});
$('#mybutton').click(function() {
if($(this).closest('form').data('changed')) {
//do something
}
});
这会为表单中的输入设置一个change
事件处理程序,如果其中任何一个发生更改,它会使用.data()
。将 changed
值设置为 true
,然后我们只需在点击时检查该值,这假设 #mybutton
在表单内(如果不只是将 $(this).closest('form')
替换为 $('#myForm')
),但你可以让它更通用,像这样:
$('.checkChangedbutton').click(function() {
if($(this).closest('form').data('changed')) {
//do something
}
});
引用:更新
根据 jQuery,这是一个选择所有表单控件的过滤器。
http://api.jquery.com/input-selector/
The :input selector basically selects all form controls.
关于javascript - 你如何处理 jQuery 中的表单更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3025396/