模式脚本在页面上始终打开相同的模式

时间:2019-11-11 07:19:47

标签: javascript

我对js不太满意

我正在尝试添加一个全局脚本来打开模式。

这是我的剧本

    class BulmaModal {
    constructor(selector) {
        this.elem = document.querySelector(selector)
        this.close_data()
    }

    show() {
        this.elem.classList.toggle('is-active')
        this.on_show()
    }

    close() {
        this.elem.classList.toggle('is-active')
        this.on_close()
    }

    close_data() {
        var modalClose = this.elem.querySelectorAll("[data-bulma-modal='close'], .modal-background")
        var that = this
        modalClose.forEach(function(e) {
            e.addEventListener("click", function() {

                that.elem.classList.toggle('is-active')

                var event = new Event('modal:close')

                that.elem.dispatchEvent(event);
            })
        })
    }

    on_show() {
        var event = new Event('modal:show')

        this.elem.dispatchEvent(event);
    }

    on_close() {
        var event = new Event('modal:close')

        this.elem.dispatchEvent(event);
    }

    addEventListener(event, callback) {
        this.elem.addEventListener(event, callback)
    }
}


const Modal = () => {
    const initModal = () => {
      if (document.querySelectorAll('.modal').length > 0) {
                var buttons = document.querySelectorAll(".toggle-modal"), i;

                for (i = 0; i < buttons.length; ++i) {
                    var target = (buttons[i].getAttribute('data-target'));
                    var mdl = new BulmaModal("#" + target)
                    buttons[i].addEventListener("click", function () {
                        mdl.show()
                    })
                }
      }
    };
    const init = () => {
      initModal();
   };
   return {
     init,
   };
};

export default Modal;

模式正在触发,但是每次它会打开相同的模式。每个模态都有一个带有目标的按钮

<button class="is-success button toggle-modal" data-target="edit-participant">
Modify User
</button>

每个模态都有一个与按钮的data target属性对应的id,因此在这种情况下

<div class="modal" id="edit-participant">
</div>

错误在哪里?

1 个答案:

答案 0 :(得分:0)

我认为您的initModal应该触发最后设置的mdl对象。您可以尝试如下更新for循环。

const initModal = () => {
if (document.querySelectorAll('.modal').length > 0) {
    var buttons = document.querySelectorAll(".toggle-modal"), i;

    for (i = 0; i < buttons.length; ++i) {
        buttons[i].addEventListener("click", function () {
            var target = this.getAttribute('data-target');
            var mdl = new BulmaModal("#" + target)
            mdl.show()
        });
    }
}