【发布时间】:2017-06-10 10:12:45
【问题描述】:
我有一个html表单如下-
<form>
<button id="btn1">Save & Add</button>
<button id="btn2">Save & Return</button>
</form>
这些按钮与我的 jquery 插件绑定如下-
$('#btn1').SwiftSave({ exit: false }, null, null, null, null, null);
$('#btn2').SwiftSave({ exit: true }, null, null, null, null, null);
这是我的插件-
(function ($) {
$.fn.SwiftSave = function (options,validationRules, onBeforeSend, onSuccess, onError, onComplete) {
return this.each(function () {
var $This = $(this);
var settings = $.extend({
....
}, options);
var $Form = $This.parents('form');
$This.on('click', function (event) {
event.preventDefault();
$Form.submit();
});
//This event fires twice
$Form.on('submit', function (event) {
event.preventDefault();
event.stopPropagation();
SubmitFormAsAuto();
});
function SubmitFormAsAuto() {
var $SeriallizedData = $Form.serialize();
$.ajax({....});
}
});
};
}(jQuery));
问题是,表单被提交了两次。我检查了按钮单击事件。它可以正常触发。问题出在其他地方。
也许 form.on('submit' ...) 已经与 $Form 变量绑定了两次。
我在这里做错了什么?
【问题讨论】:
-
你在哪里检查
options,它定义了真假退出?我相信,既然你没有检查,它提交两个按钮,因此可能是两次?? -
@MilanChheda 你想让我在这里发布 1000 行该插件吗?
-
显示的代码中没有任何内容会产生这种行为。提供minimal reproducible example
-
@charlietfl 我认为这篇文章有足够的洞察力来思考这个问题。并且不应关闭。
标签: jquery plugins jquery-plugins