问题
I have a website calendar which acts similar to a reservation request. I had this working in Bootstrap 2x but have converted the app to 3.0. Everything seems to be working, but I am trying to figure out how to dynamically change the data-target.
If a date is available, a day in the calendar may look like this:
<div id="20140226" data-id="20140226" class="NotRequested calDay" data-target="#modalDialog1" data-toggle="modal">26</div>
I have a show event that pulls the id of the day div and sets the id of the request div which works fine.
$('#modalDialog1').on('show.bs.modal', function (e) {
$(e.target).data("id", $(e.relatedTarget).data("id"));
}
In this modal, a button sends a request for the date, and if successful, swaps the class of the div to show that the date has been requested.
Here's my issue: In Bootstrap 2x I would unbind the click event, and rebind to a new click event.
In Bootstrap 3x I am trying to change the data target.
dateElement.data("target", "#modalDialog2");
When I click on this date again, I get the initial Request dialog "#modalDialog1" instead of #modalDialog2
I have also tried keeping the bind/unbind code, however, it looks like I will need to remove the modal data-toggle as now it's showing both dialogs after requesting a date.
I'm obviously missing something.
How can I dynamically change the data-target so that it will call the 2nd dialog?
回答1:
I know this is old, so I hope this is all correct.
I believe I have solved this by getting the date element above by getting the id from the request modalDialog1.
If the request was successful, then the css and click event is altered.
var dateElement = $("#" + $("#modalDialog1").data("id"));
dateElement.removeClass("NotReceived");
dateElement.unbind('click');
Then setting the new css and target
dateElement.addClass("Requested");
dateElement("target", "#modalDialog2");
Then binding the click event to the a new function to display dialog2
dateElement.bind('click', PromptDialog2Function);
回答2:
In my simple code below, the dropdownlist determines which dialog will be shown
<select onchange="$('#btn').data('target', this.value)">
<option value="#dlg1">Dialog 1</option>
<option value="#dlg2">Dialog 2</option>
</select>
<button id="btn" data-target="#dlg1" onclick="$($(this).data('target')).modal('show');">
Show Dialog
</button>
来源:https://stackoverflow.com/questions/21444595/how-to-dynamically-change-bootstrap-modal-data-target-click