关于javascript:如何在不打开模态对话框的情况下为data-toggle =“modal”按钮设置自定义点击事件处理程序?

How to set custom click event handler for data-toggle=“modal” button without opening modal dialog?

我有一个名为"HasIncreasePoint"的$.post()请求,如果从服务器返回的数据表明成功(e.IsSuccess),我不想打开引导模式对话框,并完成单击事件过程。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
$('a[data-toggle="modal"]').on('click', function (event) {
    $.post("@Url.Action("HasIncreasePoint")", function (e){
        if (e.IsSuccess) {
            alert("error!please not to open the modal!");
            event.preventDefault();
            event.stopPropagation();
            $('a[data-toggle="modal"]').off("click");
        }else{
            // From the clicked element, get the data-target arrtibute
            // which BS3 uses to determine the target modal
            var target_modal = $(e.currentTarget).data('target');
            // also get the remote content's URL
            var remote_content = e.currentTarget.href;

            // Find the target modal in the DOM
            var modal = $(target_modal);
            // Find the modal's  so we can populate it
            var modalBody = $(target_modal + ' .modal-body');

            // Capture BS3's show.bs.modal which is fires
            // immediately when, you guessed it, the show instance method
            // for the modal is called
            modal.on('show.bs.modal', function () {
                // use your remote content URL to load the modal body
                modalBody.load(remote_content);
            }).modal();

            // and show the modal

            // Now return a false (negating the link action) to prevent Bootstrap's JS 3.1.1
            // from throwing a 'preventDefault' error due to us overriding the anchor usage.
            return false;
        }
    });
});

和HTML代码:

1
    <span>SignIn</span>


您可以删除data-toggle="modal"属性并绑定.btn-check-in类。
然后,每当你需要模态时,使用javascript打开它(就像你已经做的那样)

1
  <span>SignIn</span>

JS:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// set a flag to prevent multiple requests:
var waiting = 0;

$('.btn-check-in').on('click', function(event){
  event.preventDefault();
  if(!waiting){
    var myModal = $(this).data('target');
    var remote_content = this.href;
    $.post('@Url.Action("HasIncreasePoint")').done(function(e){
      if(!e.IsSuccess){

        // this part seems to be overdone, but I left it as is
        // as I don't know what is your reason of loading fresh content each time...
        $(myModal).on('show.bs.modal', function(){
          $(this).find('.modal-body').load(remote_content);
        }).modal('show');

      }else{
        // it was successful!
      }
      waiting = 0;
    });
  }
  waiting ="I'm waiting for $.post()";
});