我了解event.preventDefault()
和event.stopImmediatePropagation()
。但它对我不起作用。在我的情况下,我有这样的ajax调用:
$('#templateConfirmDialog').on('show.bs.modal', function (event) {
$(this).find('.modal-yes').click(function(){
var form = form2js('search_form', '.', true, function (node) {}, false);
var requestData = JSON.stringify(form, replacer);
var $formErrors = $('.search_form').find('.alert-danger');
event.preventDefault();
event.stopImmediatePropagation();
$.ajax({
type: 'POST',
contentType : "application/json",
url: '/fraud/template/testCreate',
data: requestData,
dataType: 'json',
success: function (data) {
$formErrors.text('');
//if no errors just reload
if (data === undefined || data.length === 0) {
location.reload();
}
else {
//else bind error messages
data.forEach(function(error) {
$('#new-' + error.field + '-error').text(error.defaultMessage);
})
}
}
});
});
我的问题是,当我尝试输入数据时,ajax调用被阻止了很多次。如果我输入一次无效数据 - ajax被调用两次。如果两次--3次。这种行为可能是什么原因?
答案 0 :(得分:2)
每次发生此事件时:
$('#templateConfirmDialog').on('show.bs.modal', function (event) {
绑定新的单击事件处理程序:
$(this).find('.modal-yes').click(function(){
因此,如果您show.bs.modal
两次,那么您有两个click
事件处理程序都提交AJAX请求。相反,只需将click
事件处理程序绑定到目标可点击元素,而不是每次显示模态时绑定它。
替换它:
$('#templateConfirmDialog').on('show.bs.modal', function (event) {
$(this).find('.modal-yes').click(function(){
//...
});
});
有了这个:
$('#templateConfirmDialog').find('.modal-yes').click(function(){
//...
});
或者,如果该元素动态添加到DOM,则:
$(document).on('click', '#templateConfirmDialog .modal-yes', function(){
//...
});
这样,只需在页面加载时创建单击事件处理程序,而不是每次显示模态时都添加新的处理程序。