函数未按计划调用

时间:2016-12-09 10:17:53

标签: javascript html

我对JavaScript和整个网络开发都很陌生,并且真的无法理解为什么我的函数没有被正确调用。

我尝试创建一个"控制器" -class,就像我调用它一样,它包含弹出元素的Activityopen()等函数。

这是控制器类:

close()

然后我们拥有具有全局范围的控制器对象,它位于HTML的头部。

function PopupController(containerElementId){
    _containerElement = document.getElementById(containerElementId);
    _contentElement = _containerElement.getElementsByClassName("modal-body")[0];

    window.onclick = function(event) {
        if (event.target !== _containerElement && _containerElement.style.display === "block") {
            _containerElement.style.display = "none";
        }
    }
}

PopupController.prototype = {
    constructor: PopupController
}

PopupController.prototype.open = function(contentHtml) {
    _contentElement.innerHTML = contentHtml;
    _containerElement.style.display = "block";
}

PopupController.prototype.close = function() {
    _containerElement.style.display = "none";
    _contentElement.innerHTML = "";
}

和HTML。

this._popupController = new PopupController("popupContainerId");

function openPopup(){
    this._popupController.open("<p>testing</p>");
}

当我在Chrome中调试此内容时,感觉就像在页面加载时调用了<body> <button type="button" class="btn btn-info btn-lg" data-toggle="modal" onclick="openPopup()">Read more</button> <div class="popupContainer" tabindex="-1" role="dialog" id="popupContainerId"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title">Modal title</h4> </div> <div class="modal-body"> </div> <div class="modal-footer"> <button type="button" class="close">Close</button> </div> </div> </div> </div> </body> ,尽管我认为我已将其连接到按钮点击时调用。无论如何都不会显示弹出窗口,但这是另一个问题。

希望有人能给我一个关于如何进行的提示吗?

2 个答案:

答案 0 :(得分:1)

您正在HEAD标签中初始化控制器?

this._popupController = new PopupController("popupContainerId");

因为对我来说,Firefox抱怨“popupContainerId”元素不存在(尚未)。 JS在加载整个HTML之前运行。但可以是不相关的。

答案 1 :(得分:0)

对您的代码进行一点升级

  • 最好使用此方法为类属性添加前缀。
  • 无需声明&#39;构造函数&#39;,主要功能已设置为构造函数
  • 在构造函数中需要保存对这个&#39;的引用。在onclick功能
function PopupController(containerElementId){
    this._containerElement = document.getElementById(containerElementId);
    this._contentElement = this._containerElement.getElementsByClassName("modal-body")[0];

    var that = this;

    window.onclick = function(event) {
        if (event.target !== that._containerElement && that._containerElement.style.display === "block") {
            that._containerElement.style.display = "none";
        }
    }
}

https://jsfiddle.net/m1zq7otb/

相关问题