触发器等问题。事件不会触发on方法

时间:2018-12-18 21:33:54

标签: javascript jquery

基本上,我想从单击.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 });
});

1 个答案:

答案 0 :(得分:1)

要使您的代码正常工作,我必须进行一些修改。试试这个:

<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>