我有一个使用 AJAX 的大型表单,因此请保存。它使用一堆存储在外部 JS 文件中的 JS。它们看起来像这样:
function milestone09() {
$.post('./post.3.AIGs2GRA.php?data=' + (secData), $('#milestone09').serialize(), function(data) {
$("#errorText_milestone09").html(data.errorText_milestone09);
$("#resultImg_milestone09").html(data.resultImg_milestone09);
$("#errorStatusReport").html(data.errorStatusReport);
}, 'json' );
}
function dateExp09() {
$.post('./post.3.AIGs2GRA.php?data=' + (secData), $('#dateExp09').serialize(), function(data) {
$("#errorText_dateExp09").html(data.errorText_dateExp09);
$("#resultImg_dateExp09").html(data.resultImg_dateExp09);
$("#errorStatusReport").html(data.errorStatusReport);
}, 'json' );
}
function milestone10() {
$.post('./post.3.AIGs2GRA.php?data=' + (secData), $('#milestone10').serialize(), function(data) {
$("#errorText_milestone10").html(data.errorText_milestone10);
$("#resultImg_milestone10").html(data.resultImg_milestone10);
$("#errorStatusReport").html(data.errorStatusReport);
}, 'json' );
}
function dateExp10() {
$.post('./post.3.AIGs2GRA.php?data=' + (secData), $('#dateExp10').serialize(), function(data) {
$("#errorText_dateExp10").html(data.errorText_dateExp10);
$("#resultImg_dateExp10").html(data.resultImg_dateExp10);
$("#errorStatusReport").html(data.errorStatusReport);
}, 'json' );
}
等等,触发器如下:
$("document").ready(function() {
$("#milestone09").blur(milestone09);
$("#dateExp09").blur(dateExp09);
$("#milestone10").blur(milestone10);
$("#dateExp10").blur(dateExp10);
})
这只是我拥有的许多内容中的一部分 - 而且它们工作得很好。问题是,我现在正在制作一个包含大量用户输入数据表的表单,这会将一个表单的触发器和函数增加到远远超过 100 个。我必须有一种更简单的方法来编写这个 JS,而不必像这样单独定义它们,当然吗?每个文本输入字段的id和名称与触发器和后续函数名称一致。那么我不能使用某种循环函数之类的吗?欢迎咨询!
是的,我正在使用 jQuery。
最佳答案
一个非常简单的方法是获取 ID 并将其插入到正确的位置:
function blurHandler() {
var id = this.id;
$.post('./post.3.AIGs2GRA.php?data=' + secData, $('#'+id).serialize(), function(data) {
$("#errorText_"+id).html(data['errorText_'+id]);
$("#resultImg_"+id).html(data['resultImg_'+id]);
$("#errorStatusReport").html(data.errorStatusReport);
}, 'json' );
}
// If you also have textareas or selects, change this
$('input').blur(blurHandler);
关于javascript - AJAX JS 循环 - 更简单的方法来完成多个帖子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29287480/