javascript - 如何在定义之前使函数“等待”对象?
问题描述
当我单击调用 toPrevious() 函数的“上一个”按钮时,它给了我一个错误,说没有定义选择器(toPrevious() 读取的),因为选择器是在 DOMContentLoaded 之后创建的。如果我将 toPrevious() 放在 DOMContentLoaded 中,则表示未定义 toPrevious(),因为单击按钮时尚未定义 toPrevious()
如何仅在定义 DOMContentLoaded (和选择器)后才调用 toPrevious() ,但不会导致按钮出现任何问题?
HTML:
<head>
<title>Assignment 3</title>
<link href="picker.css" rel="stylesheet" />
<script type="text/javascript" src="Picker.js"></script>
<script>
document.addEventListener('DOMContentLoaded', (event) => {
const picker = new Picker(document);
function toPrevious() {
console.log("hi");
picker.toPrev(document);
}
});
</script>
</head>
<body>
<table>
<tr>
<th id="d0">{{H1}}</th>
<th id="d1">{{H2}}</th>
<th id="d2">{{H3}}</th>
<th id="d3">{{H1}}</th>
<th id="d4">{{H2}}</th>
<th id="d5">{{H3}}</th>
<th id="d6">{{H3}}</th>
</tr>
</table>
<button id="prev" onclick="toPrevious()"> Previous</button>
<button id="next" onclick="toNext()">Next</button>
</body>
</html>
Javascript:
class Picker {
/**
* Create a date picker
* @param {string} containerId id of a node the Picker will be a child of
*/
constructor(containerId) {
console.log(containerId.getElementsByTagName('body').innerHTML);
}
toPrev(document) {
console.log(document);
}
解决方案
推荐阅读
- python - Pyspark:按键聚合RDD,然后也按键汇总元组值列表
- java - 无法使用 Java 中的 WebClient 连接到特定的 https 网站
- css - Antd 水平菜单栏
- javascript - Return index of last occurrence in array
- html - CSS 和 HTML 在 Flask Jinja2 模板中不起作用
- ruby-on-rails - 无法使用 pundit 作为 user.admin 或 record.user 删除。我怎样才能让他们删除?
- swift - 当scrollView不滚动时如何复制scrollViewDidScroll的效果
- javascript - 如何在 React Native 中粘贴自定义标头
- linux - 用于在 Windows 上进行交叉编译的 Posix 头文件(专门用于提升)
- javascript - 有人可以解释一些与 for.Each() 方法相关的事情吗?