简体   繁体   English

无法动态创建模态以单击时关闭| 以.parents()打开

[英]Can't get dynamically created modal to close on click | opens with .parents()

I have a module that was built using a Handlebars.js template, I orignally had it opening and closing perfectly, but the information wasn't updated, this can be seen here . 我有一个使用Handlebars.js模板构建的模块,原本可以完美地打开和关闭它,但是信息没有更新,可以在这里看到。

Now I have it so it updates the info, but the toggleClass won't fire when clicking either the 'x' or .overlay. 现在我有了它,所以它更新了信息,但是单击“ x”或.overlay时,不会触发toggleClass。 This can be seen here . 这可以在这里看到。

Here is my jQuery functions to activate the modal. 这是我的jQuery函数,用于激活模式。

 $(document).on('click', "a.btn", function (e) {
           $(e.target).parents('.image-container').prev('.modal').toggleClass('modal--show');
        });

        $(document).on('click', '.overlay', function (e) {
            $(e.target).prev('.modal').toggleClass('modal--show');
        });

        $(document).on('click', '.modal__close', function () {
            $('.modal').toggleClass('modal--show');
        });

How can I make it so this modal will both Open and Close, as well as display the correct information? 我如何才能使此模式同时打开和关闭,以及显示正确的信息?

Some things I've tried... 我尝试过的一些事情

  • replacing: $(e.target) with $(this) $(this)替换$(e.target) $(this)

The problem with your code is that you are trying to toggle class of all .modal divs. 您的代码的问题是您试图切换所有.modal div的类。 But you need to toggle the class of only .modal.modal--show . 但是您只需要切换.modal.modal--show的类。 Also in case of overlay, you need to find the parent div not the sibling div. 同样在重叠的情况下,您需要找到父div而不是兄弟div。 So use .closest() in place of .prev() 因此,请使用.closest()代替.prev()

So if you modify your code as 因此,如果您将代码修改为

        $(document).on('click', '.overlay', function (e) {
            $(e.target).closest('.modal.modal--show').toggleClass('modal--show');
        });

        $(document).on('click', '.modal__close', function () {
            $('.modal.modal--show').toggleClass('modal--show');
        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM