简体   繁体   English

Bootstrap modal relatedTarget未定义

[英]Bootstrap modal relatedTarget is undefined

I am trying to get the clicked element using the property relatedTarget of the show.bs.modal event. 我试图让使用属性的点击的元素relatedTarget的的show.bs.modal事件。 It's always getting undefined though. 但它总是变得不确定。

This is what I have: 这就是我所拥有的:

  $("#curCarSelect").on('click', function(e) {
    $("#curCarModal").on('show.bs.modal', function(event) {
      modalOpenedby = event.relatedTarget; 
      alert(modalOpenedby);
    }).modal('toggle');
  });

try: 尝试:

$("#curCarSelect").on('click', function(e) {
   $modal.modal('toggle', $(this));
});

where $modal is your modal element to open, then: 其中$ modal是你打开的模态元素,然后:

$modal.on('show.bs.modal', function (event) {
   var button = $(event.relatedTarget) // Button that triggered the modal
})

Per the documentation : 根据文件

If caused by a click , the clicked element is available as the relatedTarget property of the event. 如果由单击引起 ,则单击的元素可用作事件的relatedTarget属性。

But you're just calling .modal('toggle') . 但你只是在调用.modal('toggle') That doesn't involve any click event , hence why relatedTarget in undefined in your case. 这不涉及任何点击事件 ,因此在您的情况下为什么relatedTarget未定义。

If you need to use event.relatedTarget in you dynamically opened modal then you can pass the target as a second argument in the modal function. 如果需要在动态打开的模态中使用event.relatedTarget ,则可以将目标作为模态函数中的第二个参数传递。

$("#curCarSelect").on('click', function(e) {
    $("#curCarModal").modal('toggle', $("#curCarSelect")); 
});

I make it worked for me. 我让它适合我。 Try this: 试试这个:

$("#curCarSelect").on('click', function(e) {
    $("#curCarModal").on('show.bs.modal', function(event) {
        modalOpenedby = event.relatedTarget; 
        alert(modalOpenedby);
    }).modal('toggle', e);
});

Workaround for this worked for me on bootstrap 2: 解决方案为我在bootstrap 2上工作:

$("a[data-toggle='modal']").on('click', function(e) {
    $_clObj = $(this); //clicked object
    $_mdlObj = $_clObj.attr('data-target'); //modal element id 
    $($_mdlObj).on('shown.bs.modal',{ _clObj: $_clObj }, function (event) {
           $_clObj = event.data._clObj; //$_clObj is the clicked element !!!
           //do your stuff here...
    });
});

try this: 试试这个:

$('#curCarModal').on('shown.bs.modal', function () {
    modalOpenedby = event.relatedTarget; 
});

$("#curCarSelect").on('click', function(e) {
    $("#curCarModal").modal('toggle'); 
    alert(modalOpenedby);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM