Bootstrap模式的自定义按钮事件多次显示

时间:2015-01-17 20:17:51

标签: javascript jquery ajax twitter-bootstrap

我有以下模态内容

<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">Modal title</h4>
            </div>
            <div class="modal-body">
                ...
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save changes</button>
            </div>
        </div>
    </div>
</div>

上述模态对话框中的内容是默认的,将替换为从ajax调用返回的内容,如下所示。

我有以下javascript代码

$(document).ready(function () {
    //This is a external button whose click opens the dialog
    $('#add_user').on('click',function(e){
    e.preventDefault();
    editPost({
        //some data for addition
    },"scripts/edituser.php");

   $('#update_user').on('click',function(e){
    e.preventDefault();
    editPost({
        //some data fro updation
    },"scripts/edituser.php");

}) ;
//editPost is the function which returns the data from server and appends it 
//to dialog and opens it.
var editPost = function(data,url){
   $.ajax({
      "url" : url,
      "type": "POST",
      "data" : data
   }).done(function(response){
        $('#editModal').empty().append(response);
        var modal = #('#editModal').modal("show");
        // The following button actually present in the modal content               returned from ajax.
        modal .on('click','button#mybutton',function(e){
            e.preventDefault();
            //This form is also present in the modal content returned from ajax call
            $form = $("form[name='myform']");
            var formData = $form.serialize();
            $.ajax({
                "url" : 'anotherurl',
                "method" : "POST",
                "data" : formData
            }).done(function(serverResponse){
               //Any event written here is triggering multiple times.
            });

   });

};
 // If I try to register any event on the button which is displayed in the modal from ajax call right here (at this place), it is not working
}

如果我尝试在从ajax内容返回的按钮上注册任何点击事件(以模态显示),则不会注册。但是如果我在模态内容中注册任何事件显示ajax'完成'回调,它工作正常。这段代码有什么问题?

另外,正如您所看到的,我在调用editPost方法的地方有两个事件。因此,如果我单击add_user然后update_user,则每次单击时事件都会相乘。

1 个答案:

答案 0 :(得分:0)

在modal和.on

之间有一个空格
modal .on('click','button#mybutton',function(e){