Rom*_*dgz 2 html javascript jquery twitter-bootstrap
我编写了代码,用于在单击按钮时显示模态,目的是在模态内编辑按钮的文本.
我的意图是有很多按钮,所以不是通过id获取它们,而是在调用模态时使用e.relatedTarget以便知道哪个按钮已调用并从按钮获取文本以便我可以在模态.
但是当我在模态下编辑文本并单击确定按钮时,问题就出现了.我不知道如何从那里访问e.relatedTarget.
HTML:
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">Change this text</button>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="exampleModalLabel">New message</h4>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="text-to-edit" class="control-label">Edit text:</label>
<input type="text" class="form-control" id="text-to-edit">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Send message</button>
</div>
</div>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
JS:
$('#exampleModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var buttonText = button.text() // Get text
// Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
var modal = $(this)
modal.find('.modal-body input').val(buttonText)
});
// Modal ok button
$('#exampleModal .btn-primary').click(function() {
// Get input text value
var text = $('#exampleModal').find('.modal-body input').text();
// Hide modal
$('#exampleModal').modal('hide');
// Set new text to the caller button
// ?
});
Run Code Online (Sandbox Code Playgroud)
JsFiddle:http://jsfiddle.net/nm4nmxsf/
有帮助吗?
我添加了评论,告诉你要改变什么
// Set an empty variable for button outside of your function !important
var button = '';
$('#exampleModal').on('show.bs.modal', function (event) {
//don't redeclare your variable for button, instead update it
button = $(event.relatedTarget) // Button that triggered the modal
var buttonText = button.text() // Get text
// Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
var modal = $(this);
modal.find('.modal-body input').val(buttonText);
});
// Modal ok button
$('#exampleModal .btn-primary').click(function() {
// Get input text value
//use val() instead of text()
var text = $('#exampleModal').find('.modal-body input').val();
$('#exampleModal').modal('hide');
// Set new text to the caller button
// ?
button.text(text);
});
Run Code Online (Sandbox Code Playgroud)
看到这个fidde:http: //jsfiddle.net/nm4nmxsf/4/
| 归档时间: |
|
| 查看次数: |
1274 次 |
| 最近记录: |