我有一个网站,包含了许多不同的联系方式。我希望保留一个ID数组(和其他相关设置),这样我就可以循环遍历它们,并向每个ID添加提交处理程序。
问题是,只有数组中的最后一个表单似乎有一个处理程序附加到它。
表格清单:
forms = [
{id: '#contact-form-1', ...},
{id: '#contact-form-2', ...}
]如何添加提交处理程序:
for (i in forms) {
$(document).on('submit', forms[i].id, function(){
// Validation, send email etc.
}
}$(document).on()是解决这个问题的正确方法吗?我尝试过$(formsi.id).submit();但是我得到了相同的结果;只有列表中的最后一个表单被绑定到。
发布于 2014-05-18 12:34:11
可能会想用相反的方法。
/* listen for ALL submit forms */
$('form').on('submit', function() {
/* get the id of the this one */
var _id = $(this).attr('id');
/* do some conditions on _ID */
));所以说你的目标是:
var formIDs = {
formidOne: { func : function() { alert('called form id one'); }},
formidTwo: { func : function() { alert('called form id two'); }}
};那就可以说:
$('form').on('submit', function() {
/* get the id of the this one */
var _id = $(this).attr('id');
/* call the form function associated with this form id */
formIDs[_id].func();
));要做到这一点,有几种方法,这都取决于您想要如何组织代码,这将更容易一些,因为只定义一次侦听器。
添加了一个编辑:因为它并没有真正解释原始代码中发生了什么问题--即i的上下文没有被正确地保留(已经在注释中暗示了)
解决方案是利用另一个功能:
function makeHandler (index) {
$('#'+forms[index].id).on('submit', function(){... });
}
for (i in forms) { makeHandler(i); }这是查找在循环How to fix jslint error 'Don't make functions within a loop.'?中生成函数的问题的最佳地方。
仍然倾向于像上面那样使用one处理程序,更易于维护/读取( imo )
发布于 2014-05-18 12:38:02
您可以在像$.each这样的闭包中这样做。
$.each(forms, function(index, item){
$(document).on('submit', forms[index].id, function(){.....
})如果没有jQuery,则可以创建for循环索引的闭包:
for (i in forms) {
(function(i){
/* your code here */
})(i);
}https://stackoverflow.com/questions/23721827
复制相似问题