javascript - 打开引导模式单击自动生成的元素
问题描述
我在使用 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();
});
解决方案
动态创建元素的问题在于,它们与现有元素的事件处理程序不同。
为了修复它,您需要在添加动态元素后“刷新”侦听器。
因此,我将事件处理程序添加到函数并在打开它之前将其关闭(例如重新启动)。如果你不关闭它,该事件将触发多次调用此函数,而你不希望它。
function refreshEvents() {
$(".openEditModal").off();
$("#add-new-box").off();
$(".openEditModal").click(function() {
$("#editBoxModal").modal();
});
$("#add-new-box").click(function() {
$("#addNewBoxModal").modal();
});
}
现在,您可以在创建另一个元素时调用此函数。所以我在你创建元素后调用它。
这是一个工作小提琴
推荐阅读
- database - 如何比较两个不同数据库中每个表的计数?
- mongodb - MongoDB合并数据库
- apache-storm - Storm 1.2.2 和 Kafka 版本 2.x
- python - 过采样类不平衡训练/测试拆分“发现样本数量不一致的输入变量”解决方案?
- playframework - 如何从 DatabaseConfigProvider 将进化应用到测试数据库
- regex - 使用或条件缩短/简化正则表达式
- c - 程序可在 onlineGDB 编译器上运行,但使用 MinGW 编译时出现逻辑错误
- javascript - 单击重置按钮后数据未附加到我们再次重新加载页面以附加数据
- r - dplyr 的多个滞后
- laravel - 在 Laravel Backpack 中编辑默认语言值时未定义的索引