Javascript 触发器和on出现问题。事件不会触发on方法

Javascript 触发器和on出现问题。事件不会触发on方法,javascript,jquery,Javascript,Jquery,基本上,我想从单击show modal时开始触发“modal:show”事件,但在触发事件时没有得到响应。我尝试了许多不同的实现,但都做不好 $(".modal").on("modal:show", function (event) { onShowModal(event.id); }); function onShowModal(modalId) { let $modal = $("#" + modalId); $modalBlack.fadeIn("slow",

基本上,我想从单击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>
生成我自己的HTML
做一个按钮
切换,切换。
$(.modal”).on(“模态:显示”,函数(事件,idObj){
//这里的技巧是第一个参数是事件。
//第二个参数是在
//触发调用。($(“.modal”).trigger…)
onshowmodel(idObj);
});
显示模式上的函数(idObj){
让$modal=$(“#”+idObj.id);
//不要忘记进入对象并获取Id。
//我没有modalBlack,所以我的代码在这一点上坏了。
$modalBlack.fadeIn(“慢”,函数(){
$modal.fadeIn(“快速”,函数(){
$modal.trigger(“modal:showing”,{id:modalId});
//莫达利德很可能就是idObj.id。
});
});
}
$(“.show modal”)。单击(函数(事件){
让modalId=$(this).data(“模态id”);
event.preventDefault();
$(“.modal”).trigger(“modal:show”,{id:modalId});
//请注意,这是作为对象{id:modalId}发送的。
});

.trigger(“模态:show”,{id:modalId})不会在事件上放置id。如果您引用,您将看到额外的参数将是传递到侦听器的额外参数,除了事件之外,它不会在没有额外参数的情况下启动,因此我认为您的代码中存在某种语法问题,但如果没有更多的代码可看,我真的不能说。