twitter bootstrap modal — how to pass data to call

2019-03-05 16:23发布

问题:

is there a way to pass additional data to bootstrap modal function callback?

for example, lets say my link that causes the modal to open has an extra attribute in it with a bit of useful data in it, how could I reference that attr?

HTML

<span listid="80" href="#editTaskList" data-toggle="modal" class="btn btn-mini right"><i class="icon-edit"></i> Edit Task List</span>

JS

$('#editTaskList').on('show', function () {
    // get the source of the click, and then get the data i need.
});

回答1:

Could this work for you ?

<span listid="80" href="#editTaskList" data-toggle="datamodal" class="btn btn-mini right"><i class="icon-edit"></i> Edit Task List</span>
var $editTaskList = $('#editTaskList');

$('body').on('click.modal.data-api', '[data-toggle="datamodal"]', function (e) {
    var $this = $(this);
    $editTaskList.data('anyAttr',$this.data('anyAttr'));
    $editTaskList.modal('show');
    e.preventDefault();
})

$editTaskList.on('show', function () {
    var myData = $editTaskList.data('anyAttr');
});


回答2:

Like this -

<span id="modal_opener" data-extrastuff="stuff" listid="80" href="#editTaskList" data-toggle="modal" class="btn btn-mini right"><i class="icon-edit"></i> Edit Task List</span>

$('#modal_opener').click(function() {
    var stuff_i_want = $(this).attr('data-extrastuff');
});


回答3:

I know that this is an old question, but this is the first thing i've found on google. So, I want to put some important information here...

You NEED to put your callback function binded on events BEFORE you call the modal, for example:

$('#modal').on('shown', function(){ 
     // Do something when the modal is loaded
});
$("#modal").modal();

This is very important and helped me a lot, so, here it is...