我有一个带有一些数据属性的按钮。当我单击它时,将显示一个模态。在此模式中,我有一个更新数据库并关闭模式的按钮。我需要在单击以显示模式的按钮中更改数据属性。有人有建议吗?请参阅最后一行代码。 e.relatedTarget在这里不起作用。
$(document).on('show.bs.modal','#myModal', function (e) {
$('#textareaID').val($(e.relatedTarget).data('text')); //the data attribute used here I need to change later
$('#listID').val($(e.relatedTarget).data('listid'));
});
$(document).on('hide.bs.modal','#myModal', function (e) {
//Clearing values before next use of modal
$('#textareaID').val('');
$('#listID').val('');
});
$(document).on('click', '#btnSave', function(e) {
var id = $('#listID').val();
var text = $('#textareaID').val();
//code here to update DB
//Now need to set the data-text attribute value to "text" variable.
$(e.relatedTarget).data('text', text); // NOT WORKING!
}
答案 0 :(得分:0)
类似的事情应该起作用,在打开模式的按钮上添加一个类,然后在保存模式时只需替换数据属性并删除“打开的”类即可。
var modal = $('.modal');
var btn = null;
$(document).on('click', '.open-modal', function(e) {
btn = $(this);
btn.addClass('opened-modal');
modal.show();
modal.find('.modal-header').append('Clicked: ' + $(this).html());
$(document).on('click', '#btnSave', function(e) {
var text = $('#myInput').val();
// code here to update DB
// Now need to set the data-text attribute value to "text" variable.
btn.attr('data-text', text);
btn.removeClass('opened-modal');
modal.hide();
});
$(document).on('click', '#btnClose', function(e) {
modal.hide();
});
});
.modal {
display: none;
background: rgba(0, 0, 0, 0.5);
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="open-modal" data-text="button">one</button>
<button class="open-modal" data-text="button">two</button>
<button class="open-modal" data-text="button">three</button>
<button class="open-modal" data-text="button">four</button>
<div class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Modal</h5>
<input id="myInput" type="text">
</div>
<div class="modal-footer">
<button type="button" id="btnSave" data-dismiss="modal">add-attr</button>
<button type="button" id="btnClose" data-dismiss="modal">close</button>
</div>
</div>
</div>
</div>