如何在每次打开时更改模态的内容

How to change content of a modal at each opening

本文关键字:模态      更新时间:2023-09-26

我有一个模态(我使用twitter bootstrap 2.3.2,我需要使用它,请不要说使用bootstrap3),我想显示基于点击按钮不同的内容。换句话说,有多个按钮被动态添加到dom中,我需要根据单击的按钮显示不同的内容。目前,无论我在哪里点击,它总是显示第一个点击按钮的内容。下面是我的代码:

<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true"> × </button>
        <h3 id="myModalLabel">Query Name</h3>
    </div>
    <div class="modal-body">
       <div id="graph" style="position:relative;overflow:hidden;cursor:default;" class="{{getViewType}}">
           <center id="splash" style="padding-top:230px;">
               <img src="../images/loading.gif">
           </center>
       </div>
    </div>
    <div class="modal-footer">
        <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
    </div>
</div>
这是我的处理器:
$(document).on('hidden','#myModal',function(){
    console.log('it comes here');  // this is printed every time I close modal
     $(this).removeData('modal');
});

检查动态添加的按钮的id是否唯一。此外,任何函数代码,将运行时,点击它们,也动态添加,否则它将无法运行。看到按钮的代码当然会有帮助。

DEMO

好吧. .在这种情况下,我更喜欢modal.shown事件,并使用全局变量来存储点击button的数据,如下所示

var dataToShow=""; //global variable
//A button click event to store data
$('button').on('click',function(){
    dataToShow=$(this).text();//For DEMO purpose am storing text of button clicked in dataToShow
});

$(document).on('shown','#myModal',function(){
    //Will be triggered when modal is opened
    alert(dataToShow);//Just for verification
    $('.modal-body .datadisplay').html(dataToShow); 
    //assign the value in a separate div inside modal-body so that you will not replace anything else each time
});

既然button是动态创建的,我建议在这里使用event delegationevent附加到button

$(document).on('click','.yourbuttonClass',function(){
     dataToShow=$(this).text();
});

现在如果你愿意,你可以使用

$(document).on('hidden',"#myModal",function(){
    //clear the contents inside an element added i.e. .datadisplay inside modal-body
    $('.modal-body .datadisplay').empty();   
})