首页 > 解决方案 > 如何在定义之前使函数“等待”对象?

问题描述

当我单击调用 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);
  }

标签: javascripthtml

解决方案


推荐阅读