首页 > 解决方案 > 打开引导模式单击自动生成的元素

问题描述

我在使用 Javascript 生成的元素打开 Bootstrap 4 模式时遇到问题。有两张非常相似的卡片(相同但具有不同的 ID)。首先是在 html doc 中硬编码(并且可以正常工作)。另一个是由简单的 JS 脚本生成的。我尝试使用相同的类名“openEditModal”,但它不起作用。然后我为两者声明了“数据切换”“数据目标”属性,但仍然只能使用硬编码卡。Bootstrap JS 文件是否有可能仅适用于硬编码元素?

HTML 编码卡

<div class="row" id="all-contacts-box">
        <!-- ____EXIST_ADDRESSES____ -->
        <!-- addressBoxWrapper -->
        <div class="col-xl-3 col-md-4 col-sm-6 col-12 mt-2 d-flex">
            <!-- addressBox -->
            <div class="card bg-light openEditModal label flex-fill">
                <!--contactHeader-->
                <div class="card-header pl-2 pt-1 font-weight-bold text-muted label-title">
                    Office Address
                </div>
                <!-- contactBody -->
                <div class="card-body row pt-0">
                    <!-- contactBodyLeft -->
                    <div class="col-4 d-flex justify-content-center align-items-center maps-pin">
                        <i class="fas fa-map-marker-alt"></i>
                    </div>
                    <!-- contactBodyRight -->
                    <div class="col-8">
                        <h4 class="label-title font-weight-bold">Main Name</h4>
                        <h5 class="label-address font-weight-normal">Street 22</h5>
                        <h5 class="label-address font-weight-normal">City, Country</h5>
                    </div>
                </div>
            </div>
        </div>

生成新卡片的部分JS代码

var createContactBox = function(dataToDisplay, idCounter) {
  var mainAddressContainer = document.getElementById("all-contacts-box");
  var addNewBox = document.getElementById("add-new-box");

  var addressBoxWrapper = document.createElement("div");
  var addressBox = document.createElement("div");

  mainAddressContainer.insertBefore(addressBoxWrapper, addNewBox);

  addressBoxWrapper.appendChild(addressBox);
  addressBoxWrapper.classList = "col-xl-3 col-md-4 col-sm-6 col-12 mt-2 d- 
 flex";
  addressBox.classList = "card bg-light openEditModal label flex-fill";

  addressBox.setAttribute("data-toggle", "modal");
  addressBox.setAttribute("data-target", "editBoxModal");
};

 $(".openEditModal").click(function() {
   $("#editBoxModal").modal();
 });

标签: javascriptbootstrap-modal

解决方案


动态创建元素的问题在于,它们与现有元素的事件处理程序不同。

为了修复它,您需要在添加动态元素后“刷新”侦听器。

因此,我将事件处理程序添加到函数并在打开它之前将其关闭(例如重新启动)。如果你不关闭它,该事件将触发多次调用此函数,而你不希望它。

function refreshEvents() {
  $(".openEditModal").off();
  $("#add-new-box").off();

  $(".openEditModal").click(function() {
    $("#editBoxModal").modal();
  });

  $("#add-new-box").click(function() {
    $("#addNewBoxModal").modal();
  });
}

现在,您可以在创建另一个元素时调用此函数。所以我在你创建元素后调用它。

这是一个工作小提琴


推荐阅读