加载克隆的模式(引导程序)

时间:2018-11-06 14:05:49

标签: javascript jquery twitter-bootstrap bootstrap-4 bootstrap-modal

是否可以使用引导程序加载新克隆的模态?

我需要加载许多不同的模态,但是下面是尝试仅加载一个新模态的示例。

我已经看到了有关在模态中加载克隆元素的问题,但在完全克隆的模态中却没有。

在这里摆弄这个问题:http://jsfiddle.net/hde13s2t/6/

步骤:

  1. 用户单击“克隆”以克隆模式

  2. Javascript克隆模式,并将适当的标签重命名为“克隆”(按钮和模式标签)

  3. 用户单击克隆的模态->“启动演示模态2”

html全部加载适当,但是新的模式不会触发。

HTML:

<!-- Button trigger modal -->
<div id="launchmodal1">

  <button type="button" class="btn btn-primary" data-toggle="modal" id="examplemodalbutton1" data-target="#exampleModal1">
    Launch demo modal 1
  </button>

  <!-- Modal -->
  <div class="modal fade" id="exampleModal1" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          ...
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
          <button type="button" class="btn btn-primary">Save changes</button>
        </div>
      </div>
    </div>
  </div>
 </div>
</div>
<button type="button" class="btn btn-secondary" id="clicktoclone">Clone</button>

Javascript:

$(document).on("click", "#clicktoclone", function() {
    var secondmodal = $("#launchmodal1").clone();

  // updating button id and data-target for modal 2
  secondmodal.find("#examplemodalbutton1").attr("id", "examplemodalbutton2").attr("data-target", "exampleModal2").html("Launch demo modal 2");

  // updating modal id for modal 2
  secondmodal.find("#exampleModal1").attr("id", "examplemodal2");

  secondmodal.appendTo('#launchmodal2');
});

1 个答案:

答案 0 :(得分:1)

jQuery.clone不会为新的DOM元素克隆引导事件。因此,您必须在将新的模式附加到DOM树之后设置模式调用:

$(document).on("click", "#clicktoclone", function() {
    var secondmodal = $("#launchmodal1").clone();

  // updating button id and data-target for modal 2
  secondmodal.find("#examplemodalbutton1").attr("id", "examplemodalbutton2").attr("data-target", "exampleModal2").html("Launch demo modal 2");

  // updating modal id for modal 2
  secondmodal.find("#exampleModal1").attr("id", "examplemodal2");

  secondmodal.appendTo('#launchmodal2');

  // set new click event to show the cloned modal
  $('#examplemodalbutton2').on('click', function() {
    $('#examplemodal2').modal();
  })
});

如果您有多个模式克隆,则可以将全局单击事件侦听器绑定到所有模式按钮:

  $(document).on('click', '.btn', function() {
    var targetSelector = $(this).data('target');
    $(targetSelector).modal();
  })