基本上我想在单击 .show-modal 时触发“modal:show”事件,但是当我触发该事件时没有得到任何响应。我尝试了许多不同的实现,但无法得到正确的结果。
$(".modal").on("modal:show", function (event) {
onShowModal(event.id);
});
function onShowModal(modalId) {
let $modal = $("#" + modalId);
$modalBlack.fadeIn("slow", function () {
$modal.fadeIn("fast", function () {
$modal.trigger("modal:showing", { id: modalId });
});
});
}
$(".show-modal").click(function (event) {
let modalId = $(this).data("modal-id");
event.preventDefault();
$(".modal").trigger("modal:show", { id: modalId });
});
最佳答案
为了让您的代码正常工作,我必须进行一些修改。试试这个:
<div class="modal">Generate my own HTML</div>
<div class="show-modal" data-modal-id="randomId">Make a button</div>
<div class="randomId" >Toggle, toggle.</div>
<script>
$(".modal").on("modal:show", function (event, idObj) {
// The trick here is that the first parameter is the event.
// The second parameter is the object that you send in on the
// triggering call. ($(".modal").trigger...)
onShowModal(idObj);
});
function onShowModal(idObj) {
let $modal = $("#" + idObj.id);
// Don't forget to go into the object and get the Id.
// I don't have modalBlack so my code broke at this point.
$modalBlack.fadeIn("slow", function () {
$modal.fadeIn("fast", function () {
$modal.trigger("modal:showing", { id: modalId });
// modalId is probably going to be idObj.id.
});
});
}
$(".show-modal").click(function (event) {
let modalId = $(this).data("modal-id");
event.preventDefault();
$(".modal").trigger("modal:show", { id: modalId });
// Notice that you are sending this as an object {id:modalId}.
});
</script>
关于javascript - 触发器和打开问题。事件不会触发 on 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53841414/