JavaScript Object Literal" this"

时间:2016-12-24 06:57:33

标签: javascript javascript-events javascript-objects

我写了一个JavaScript对象文字来处理HTML页面上的多个模态。 当我点击按钮显示模态时,我收到以下错误。

Uncaught TypeError: this.showModal is not a function
    at HTMLButtonElement.modalBtns.(anonymous function).onclick (file:///C:/dj-sites/ux_bee/js/base.js:63:22)

我认为问题在于"这个"关键字指向按钮,但不指向对象文字。不知道我该怎么办呢。

var myModalObj = {
    findAncestor: function(el, cls) {
        while ((el = el.parentElement) && !el.classList.contains(cls));
        return el;
    },
    showModal: function(btn){
        var modal_id = btn.getAttribute('data-modal')
        var modal = document.getElementById(modal_id);
        modal.style.display = "block";
    },
    closeModal: function (btn){
        var modal = this.findAncestor(btn, 'modal')
        modal.style.display = "none";
    },
    init: function(){
        var modalBtns = document.getElementsByClassName('my-modal-btn');
        for(var i = 0; i < modalBtns.length; i++) {
            var btn_modal = modalBtns[i];
            modalBtns[i].onclick = function() {
                this.showModal(btn_modal);
            }
        }

        var closeBtns = document.getElementsByClassName('modal-close');
        for(var i = 0; i < closeBtns.length; i++) {
            var btn_close = closeBtns[i];
            closeBtns[i].onclick = function() {
                this.closeModal(btn_close);
            }
        }
    }
}
myModalObj.init()

1 个答案:

答案 0 :(得分:0)

简单回答 - 只需将gtest的所有实例替换为this,就像这样。

myModalObj

您必须这样做的原因是因为您尝试呼叫的功能仅存储在var myModalObj = { findAncestor: function(el, cls) { while ((el = el.parentElement) && !el.classList.contains(cls)); return el; }, showModal: function(btn){ var modal_id = btn.getAttribute('data-modal') var modal = document.getElementById(modal_id); modal.style.display = "block"; }, closeModal: function (btn){ var modal = myModalObj.findAncestor(btn, 'modal') modal.style.display = "none"; }, init: function(){ var modalBtns = document.getElementsByClassName('my-modal-btn'); for(var i = 0; i < modalBtns.length; i++) { var btn_modal = modalBtns[i]; modalBtns[i].onclick = function() { myModalObj.showModal(btn_modal); } } var closeBtns = document.getElementsByClassName('modal-close'); for(var i = 0; i < closeBtns.length; i++) { var btn_close = closeBtns[i]; closeBtns[i].onclick = function() { myModalObj.closeModal(btn_close); } } } } myModalObj.init() 中,因此这是您可以调用它的唯一方式。