【问题标题】:Trying to change attribute on button that launched a modal, when clicking a button in the modal单击模式中的按钮时,尝试更改启动模式的按钮上的属性
【发布时间】:2019-07-12 14:32:15
【问题描述】:

我有一个带有一些数据属性的按钮。当我单击它时,会显示一个模式。在这个模态中,我有一个更新 DB 并关闭模态的按钮。我需要更改我单击的按钮中的数据属性以显示模式。有人有建议吗?见最后一行代码。 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!
}

【问题讨论】:

  • 您是否在控制台中遇到任何错误?你的#btnSave点击函数上没有结尾);。

标签: jquery twitter-bootstrap bootstrap-modal


【解决方案1】:

这样的事情应该可以工作,向打开模式的按钮添加一个类,然后在保存模式时只需替换数据属性并删除“打开”类。

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) {
    var btn = null;
    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>

【讨论】:

  • 实际上它没有用...我忘了提到我有多个按钮(表格中每行都有一个按钮)。我需要将值设置为仅被单击的按钮,而不是所有按钮。
  • @JamesT 回答已编辑,只需将模态保存功能放在模态打开函数中,这样我们就可以为按钮设置一个变量,并且可以在模态保存中访问它。
猜你喜欢
  • 2020-07-10
  • 1970-01-01
  • 1970-01-01
  • 2012-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-13
  • 1970-01-01
相关资源
最近更新 更多