簡體   English   中英

當引導模式關閉時,我如何知道點擊了哪個按鈕?

[英]How do I know which button is clicked when the bootstrap modal closes?

這是我的模態html代碼:

<div class="modal fade" id="delete-file-modal" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <form class="form-horizontal" method="post" id="delete_file_form">

                <div class="modal-body">
                    Are you sure you want to delete this file?  
                </div>  

                <div class="modal-footer">
                    <button data-dismiss="modal" class="btn btn-danger" name="in_confirm_insert" id="confirm-delete-button">Delete</button>
                    <button data-dismiss="modal" class="btn btn-default" name="in_confirm_insert" id="cancel-delete-button">Cancel</button>
                </div>

            </form>
        </div>
    </div>
</div>

這是我的javascript代碼:

$('#delete-file-modal').on('hidden.bs.modal', function (e) {

    var delete_button = $(e.target).is("#confirm-delete-button");

    if(delete_button === true) {
        //delete file
        alert("file deleted.");
    } else {
        alert("delete failed.");
    };
});

我需要能夠檢查刪除文件模式關閉時是否單擊了刪除按鈕。 我的 javascript 代碼中是否還缺少其他內容?

選項1

hidden.bs.modal事件偵聽器中, event.target引用隱藏的模態元素,而不是觸發事件的單擊元素。

如果要確定觸發模式關閉的按​​鈕,則一個選項是將事件偵聽器添加到模式內的按鈕元素。 然后在按鈕事件偵聽器內部,您可以偵聽父#modal元素上的hidden.bs.modal事件,以確定模式是否已關閉。 由於hidden.bs.modal事件偵聽器位於按鈕click事件偵聽器內,因此您仍然可以引用觸發click事件的元素。

這里的例子

$('#delete-file-modal .modal-footer button').on('click', function(event) {
  var $button = $(event.target); // The clicked button

  $(this).closest('.modal').one('hidden.bs.modal', function() {
    // Fire if the button element 
    console.log('The button that closed the modal is: ', $button);
  });
});

還值得一提的是.one()方法只會在每次附加時觸發事件(這正是我們想要的)。 否則,如果您使用的.on().click()附加的事件,則因為它是每個時間重新連接的事件可能觸發多次click事件監聽器被觸發。


選項#2

據相關引導文件 ,該show.bs.modal / shown.bs.modal事件有relatedTarget連接到事件屬性。

如果由單擊引起,則單擊的元素可用作事件的relatedTarget屬性。

因此,您可以通過訪問模態show事件偵聽器中的event.relatedTarget來確定觸發模式以打開事件的元素:

這里的例子

$('#delete-file-modal').on('show.bs.modal', function (event) {
    console.log(event.relatedTarget);
});

請記住, relatedTarget屬性僅與模態show事件相關聯。 如果他們有一個與hide.bs.modal / hidden.bs.modal事件相關的屬性, hide.bs.modal hidden.bs.modal 在寫這篇文章時,目前還沒有


選項#3

正如Andrew 下面的評論中指出的那樣,您還可以通過訪問document.activeElement來查看頁面上哪個元素具有焦點。

在下面的代碼段中,事件偵聽器附加到show和hide事件的模態元素。 觸發事件時,將檢查當前關注的元素是否具有[data-toggle][data-dismiss]屬性(這意味着它確實觸發了事件)。

這里的例子

$('#delete-file-modal').on('hide.bs.modal show.bs.modal', function(event) {
  var $activeElement = $(document.activeElement);

  if ($activeElement.is('[data-toggle], [data-dismiss]')) {
    console.log($activeElement);
  }
});

如果您正在收聽顯示/隱藏事件(如上例中所示),並且您想要區分事件,則可以檢查event.type

這里的例子

$('#delete-file-modal').on('hide.bs.modal show.bs.modal', function(event) {
  var $activeElement = $(document.activeElement);

  if ($activeElement.is('[data-toggle], [data-dismiss]')) {
    if (event.type === 'hide') {
      // Do something with the button that closed the modal
      console.log('The button that closed the modal is: ', $activeElement);
    }

    if (event.type === 'show') {
      // Do something with the button that opened the modal
      console.log('The button that opened the modal is: ', $activeElement);
    }
  }
});

這也有效:

$('#myModal').on('hide.bs.modal', function (e) { 
var tmpid = $(document.activeElement).attr('id'); alert(tmpid); 
}); 

它不會在模態上獲得'X'的id,除非你識別它。 將返回觸發模態關閉的元素的id ....

擴展@Jos​​hCrozier的答案:

如果他們有一個與hide.bs.modal / hidden.bs.modal事件相關的屬性,那就太好了。 在寫這篇文章時,目前還沒有


這將模擬一個類似的行為,將單擊的按鈕作為relatedTarget附加到以后的偵聽器:

$( '.modal-footer .btn[data-dismiss="modal"]' ).on( 'click', function() {
    var target = this

    $( target ).closest( '.modal' )
        .one( 'hide.bs.modal hidden.bs.modal', function( event ) {
            event.relatedTarget = target
        } )
} )

可以根據項目中模態的使用方式進一步優化選擇器和監聽器。 例如:如果你知道你不打算使用hide.bs.modal你可以改為修改hidden.bs.modal的事件。

@JoshCrozier答案是好的和有用的,但有時我們需要確定巫婆元素觸發模態在它關閉后打開/關閉。 @Nomad在下面的評論中提到了這個@JoshCrozier的回答)。

有時我們需要確定bodyheader中的哪個鏈接或按鈕觸發關閉模式(而不僅僅是footer按鈕)。

然后我寫這個解決方案, 以我的方式 混合 @JoshCrozier @Katia 答案,並改進最終的解決方案

將此部分添加到頁面的腳本中:

$('body').on('click','.modal .dismiss-modal', function() {
    var closeRelatedTarget = this;
    var $modal = $(closeRelatedTarget).closest('.modal');
    $modal.one('hide.bs.modal hidden.bs.modal', function(event) {
        $modal.data('closeRelatedTarget',closeRelatedTarget);
    });
    $modal.data('closeRelatedTarget','wait');
    $modal.modal('hide');
});
$('body').on('show.bs.modal','.modal', function(event){
    $(this).data('closeRelatedTarget','anElement');
    $(this).data('showRelatedTarget',event.relatedTarget);
});

現在可以使用簡單的事件處理程序或獲取目標元素輕松使用它:

●確定女巫元件觸發模態來顯示showshown (一個嵌入引導功能):

 $('#MyModal').on('show.bs.modal', function (event) {
     console.log(event.relatedTarget);
 });

 $('#MyModal').on('shown.bs.modal', function (event) {
     console.log(event.relatedTarget);
 });

●確定巫婆元素觸發hidden的模態關閉

 $('#BuyModal').on('hidden.bs.modal', function (event) {
      if($(this).data('closeRelatedTarget')=='wait')
      {return;}

      console.log($('#MyModal').data('closeRelatedTarget'));
 });

●確定巫元素觸發模式, 甚至顯示模式被關閉后

 console.log($('#MyModal').data('showRelatedTarget'));

●確定巫元素觸發模式, 關閉甚至模態關閉后

 console.log($('#MyModal').data('closeRelatedTarget'));

注意:而不是data-dismiss="modal"屬性使用我的modal-dismiss類到模型中的每個元素,你可以關閉模​​型並且你想要確定它(不要同時使用modal-dismiss類和data-dismiss="modal"在一起)。

示例: <a href="/more_info.html" class="dismiss-modal">More info</a>

為什么? 因為data-dismiss="modal"關閉模型並在我們設置closeRelatedTarget之前觸發隱藏和隱藏。

我們正在思考這個問題。 它就像標准的按鈕處理程序一樣簡單。 data-dismiss =“modal”將使對話框消失,我們仍然會知道我們感興趣的按鈕被點擊了。

$('#delete-file-modal').on('click','#delete-file-modal #confirm-delete-button', function (e) {
  e.preventDefault();
  console.log('confirmed delete');
  return false;
});

一個“純 js”解決方案(在引導調用函數中)適用於 BOOTSTRAP 4+,我在這里沒有看到,可以適用於其他版本,包括 v5。 如果需要,可能對某人有用。

編輯:一個與 BOOTSTRAP 4+ 配合良好的解決方案,我在這里沒有看到,可以適用於其他版本,包括 v5。 如果需要,可能對某人有用。

<div class="modal-footer">
    <button type="button" class="btn btn-secondary" data-dismiss="modal">Annuler</button>
    <button type="button" class="btn btn-primary" data-dismiss="modal">Valider</button>
</div>

$('#prompt_modal').on('shown.bs.modal', function (event) {
    let buttons = this.querySelectorAll('.btn'); // or others selectors
    buttons.forEach(btn => {
        btn.onclick = () => {
            console.log(btn);
            // do something with btn (textCOntent, dataset, classlist, others) 
            // to detect clicked...
        }
    })
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM