我对 JavaScript 和 Web 开发都很陌生,真的无法理解为什么我的函数没有被正确调用。
我正在尝试创建一个“ Controller ”类,就像我所说的那样,其中包含诸如 open()
和 close()
等函数弹出元素。
这是 Controller 类:
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 = "";
}
然后我们就有了具有全局作用域的 Controller 对象,它位于 HTML 的头部。
this._popupController = new PopupController("popupContainerId");
function openPopup(){
this._popupController.open("<p>testing</p>");
}
还有 HTML。
<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">×</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>
当我在 Chrome 中调试它时,感觉就像在页面加载时调用了 open()
,尽管我认为我已将其连接为在单击按钮时调用。弹出窗口无论如何都不会显示,但这是另一个问题。
希望有人能给我一些如何继续的提示?
最佳答案
您正在 HEAD 标记中初始化 Controller 吗?
this._popupController = new PopupController("popupContainerId");
因为对我来说,Firefox 提示“popupContainerId”元素还不存在。 JS 在整个 HTML 加载之前运行。但也可能不相关。
关于javascript - 函数未按计划调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41058073/