//对话框
//生成对话框
function createDialog(){
if ($("#dialog").length == 0){
var str = '<p class="modal fade" id="dialog" tabindex="-1" role="dialog">';
str += '<p class="modal-dialog">';
str += '<p class="modal-content">';
str += '<p class="modal-header">';
str += '<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>';
str += '<h4 class="modal-title">对话框</h4>';
str += '</p>';
str += '<p class="modal-body"><p class="text-center"><i class="icon-spinner icon-spin"></i></p></p>';
str += '<p class="modal-footer">'
str += '<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>';
str += '<button type="submit" class="btn btn-primary">确定</button>';
str += '</p>'
str += '</p>'
str += '</p>'
str += '</p>'
$(str).appendTo('body');
}
}
$('*[data-target="#dialog"]').click(function(){
createDialog();
$('#dialog').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget);
var action = button.data('action');
var modal = $(this);
switch(action)
{
case 'add':
modal.find('.modal-dialog').addClass('modal-lg');
modal.find('.modal-title').text('添加用户');
modal.find('.modal-body').html('这里是表单');
modal.find('.modal-footer button[type="submit"]').removeClass('btn-danger').addClass('btn-primary').text ('添加');
alert('1'); //测试
break;
}
});
//关闭对话框后清除modal中数据
$("#dialog").on("hidden.bs.modal", function() {
$(this).removeData("bs.modal");
});
})
htmlcode
<button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#dialog" data-action="add">添加</button>
When the add button is clicked, alert('1') will be executed first, and then the dialog box will pop up. After I close the dialog box, and then click add, the alert('1') will be executed twice. That is to say, I will receive two warning boxes, but the modal dialog box will pop up after alert('1') is completed. If you close the Modal dialog box and click the button again, alert('1') will be executed three times, and so on.
Then can I understand that the following code will be executed multiple times depending on the number of times the button is clicked.
case 'add':
modal.find('.modal-dialog').addClass('modal-lg');
modal.find('.modal-title').text('添加用户');
modal.find('.modal-body').html('这里是表单');
modal.find('.modal-footer button[type="submit"]').removeClass('btn-danger').addClass('btn-primary').text ('添加');
alert('1'); //测试
break;
So, how should I solve this problem?
Actually, it can be solved like this. I am not a front-end person, but I have encountered this kind of problem.
The first method: define the event outside the click event
The second method: remove the event first and then bind the event
I have never been able to figure out the reason for this problem. Now my brute force solution is to remove() the dialog box after closing the dialog box, and the problem is solved.
JS code