Javascript 当引导模式关闭时,我如何知道点击了哪个按钮?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28270333/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:32:12  来源:igfitidea点击:

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

javascriptjqueryhtmltwitter-bootstrap

提问by Nomad

Here is my modal html code:

这是我的模态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>

and here is my javascript code:

这是我的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.");
    };
});

I need to be able to check if the delete button is clicked when the delete-file-modal is closed. Is there something else missing in my javascript code?

我需要能够检查删除文件模式关闭时是否单击了删除按钮。我的 javascript 代码中是否还缺少其他内容?

回答by Josh Crozier

Option #1

选项1

Within the hidden.bs.modalevent listener, event.targetrefers to the modal element that is hidden, notthe clicked element that triggered the event.

hidden.bs.modal事件侦听器中,event.target指的是隐藏的模态元素,而不是触发事件的点击元素。

If you want to determine which button triggered the modal to close, one option is to add event listeners to the button elements inside of the modal. Then inside of the button event listener you could listen to the hidden.bs.modalevent on the parent #modalelement in order to determine if the modal was closed. Since the hidden.bs.modalevent listener is inside of the button clickevent listener, you still have a reference to the element that triggered the clickevent.

如果要确定哪个按钮触发了模态关闭,一种选择是向模态内的按钮元素添加事件侦听器。然后在按钮事件侦听器内部,您可以侦听hidden.bs.modal#modal元素上的事件,以确定模态是否已关闭。由于hidden.bs.modal事件侦听器位于按钮事件侦听器内部,因此click您仍然可以引用触发click事件的元素。

Example Here

示例在这里

$('#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);
  });
});

It's also worth mentioning that the .one()methodwill only fire the event once each time it is attached (which is exactly what we want). Otherwise, if you used .on()or .click()to attach the event, then the event could fire multiple times since it is reattached each time the clickevent listener is fired.

还值得一提的是,该.one()方法每次附加时只会触发一次事件(这正是我们想要的)。否则,如果您使用.on().click()附加事件,则该事件可能会触发多次,因为每次click触发事件侦听器时都会重新附加该事件。



Option #2

选项#2

According to the relevant Bootstrap documentation, the show.bs.modal/shown.bs.modalevents have a relatedTargetproperty attached to the event.

根据相关的Bootstrap 文档show.bs.modal/shown.bs.modal事件具有relatedTarget附加到事件的属性。

If caused by a click, the clicked element is available as the relatedTargetproperty of the event.

如果由点击引起,被点击的元素可用作relatedTarget事件的属性。

Thus, you can determine the element that triggered the modal to open event by accessing event.relatedTargetinside of the modal show event listener:

因此,您可以通过访问event.relatedTarget模态显示事件侦听器的内部来确定触发模态打开事件的元素:

Example Here

示例在这里

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

Keep in mind that the relatedTargetproperty is only associated with the modal show events. It would be nice if they had a property like that associated with the hide.bs.modal/hidden.bs.modalevents. As of writing this, there currently isn't.

请记住,该relatedTarget属性仅与模态显示事件相关联。如果他们有一个与hide.bs.modal/hidden.bs.modal事件相关联的属性,那就太好了。在撰写本文时,目前还没有.



Option #3

选项#3

As Andrew pointed out in the commentsbelow this answer, you can also check to see which element on the page has focus by accessing document.activeElement.

正如安德鲁此答案下方的评论中指出的那样,您还可以通过访问document.activeElement.

In the snippet below, an event listener is attached to the modal element for the show and hide events. When the event is triggered, a check is made to see if the currently focused on element has a [data-toggle]or [data-dismiss]attribute (which implies that it did in fact trigger the event).

在下面的代码片段中,事件侦听器附加到显示和隐藏事件的模态元素。当事件被触发时,会检查当前关注的元素是否具有[data-toggle]or[data-dismiss]属性(这意味着它确实触发了事件)。

Example Here

示例在这里

$('#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);
  }
});

If you are listening to both show/hide events, like in the example above, and you want to differentiate between the events, you could check event.type:

如果您正在收听显示/隐藏事件,如上例所示,并且您想区分这些事件,您可以检查event.type

Example Here

示例在这里

$('#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);
    }
  }
});

回答by Andrew

This works too:

这也有效:

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

It won't get the id of the 'X' on the modal unless you id it. Will return the id of the element which triggers the closing of the modal....

除非您指定它,否则它不会在模态上获得“X”的 id。将返回触发模态关闭的元素的 id....

回答by Katai

To extend @JoshCrozier's answer:

扩展@Jos​​hCrozier 的回答:

It would be nice if they had a property like that associated with the hide.bs.modal/hidden.bs.modal events. As of writing this, there currently isn't

如果他们有一个与 hide.bs.modal/hidden.bs.modal 事件相关联的属性,那就太好了。在撰写本文时,目前没有



This will emulate a similar behaviour, that attaches the clicked button as relatedTarget for later listeners:

这将模拟类似的行为,将单击的按钮附加为 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
        } )
} )

The selector and listener can be further optimized depending on how the modals are used in a project. For example: if you know you're not going to use hide.bs.modalyou can just modify hidden.bs.modal's event instead.

选择器和侦听器可以根据项目中模态的使用方式进一步优化。例如:如果您知道自己不会使用hide.bs.modal,则可以hidden.bs.modal改为修改's 事件。

回答by RAM

The @JoshCrozieranswer is good and useful but sometimes we need to Determine witch element triggered the modal to opened/closed AFTER it has been closed.(@Nomadhas mentioned to this in the comments below the @JoshCrozieranswer).

@JoshCrozier答案是好的,有用的,但有时我们需要确定巫元素触发模式来打开/关闭后,它已关闭。@Nomad@JoshCrozier回答下面的评论中提到了这一点)。

Also some times we need to determine which link or button in the bodyor headertriggered the modal to close (not just buttons in the footer).

此外,我们需要一些时间来确定哪些链接或按钮bodyheader触发模式接近(在不只是按钮footer)。

Theni write this solution to mix@JoshCrozierand@Katiaanswers with my way and improve the final solution:

然后我写了这个解决方案,以我的方式混合@JoshCrozier@Katia 的答案并改进最终解决方案

Add this part to Scripts of your page:

将此部分添加到页面的脚本中:

$('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);
});


Now use it easily with simple Event Handlers or Get the target element:

现在通过简单的事件处理程序轻松使用它或获取目标元素:

● Determine witch element triggered the modal to showon showand shown(An embed Bootstrap feature):

● 确定女巫元素触发模式显示showshown(嵌入引导功能)

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

and

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


● Determine witch element triggered the modal to closeon hidden

●确定巫元素触发模式来关闭hidden

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

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


● Determine witch element triggered the modal to showeven after the modal is closed

● 确定女巫元素触发模态即使在模态关闭后仍显示

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


● Determine witch element triggered the modal to closeeven after the modal is closed

● 确定女巫元素触发模态关闭,即使模态关闭

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


Note:Instead of data-dismiss="modal"property use my modal-dismissclass to each element in the model that you can close the model and you want determine it (Don't use both modal-dismissclass and data-dismiss="modal"together).

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

Why?Because data-dismiss="modal"close the model and trigger hide and hidden before we set 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

回答by Volomike

We're overthinking this. It's as simple as a standard button handler. The data-dismiss="modal" will make the dialog go away, and we'll still know that the button that we were interested in was clicked.

我们多虑了。它就像标准按钮处理程序一样简单。data-dismiss="modal" 将使对话框消失,我们仍然会知道我们感兴趣的按钮被点击了。

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