javascript 中未捕获的类型错误

Uncaught TypeError in javascipt

我一直在尝试使用 this 关键字来获取 dataset 但我一直在获取 Uncaught TypeError: Cannot read property 'page' of undefined,在下面的脚本中我想要实现的是每当单击一个按钮时,它就会显示某些内容并隐藏所有其他内容

<!DOCTYPE html>
<html>
    <head>
        <title>Show Page</title>
        <script>
            function showPage(division){
                document.querySelectorAll('h1').style.display = 'none';
                document.querySelector(divsion).style.display = 'block';
            }
            document.addEventListener('DOMContentLoaded',() => {
                document.querySelectorAll('button').forEach(button => {
                    button.onclick = () => {
                        showPage(this.dataset.page);
                    } 
                });
            });
        </script>
    </head>
    <body>      
        <button data-page="page1">Page1</button>
        <button data-page="page2">Page2</button>
        <button data-page="page3">Page3</button>
        <h1 id="page1">This is page1</h1>
        <h1 id="page2">This is page2</h1>
        <h1 id="page3">This is page3</h1>
    </body>
</html>

在您的点击处理程序中使用 function() {},以便处于正确的上下文中。箭头函数保留周围的上下文:

document.querySelectorAll('button').forEach(button => {
  button.onclick = function() {
    console.log(this.dataset.page);
  }
});
<button data-page="page1">Page1</button>
<button data-page="page2">Page2</button>
<button data-page="page3">Page3</button>

如果你使用arrow function那么this将不会包含当前元素,你需要在function中传递一个parameter(event),得到它的current target 然后获取属性。

function showPage(division) {
  document.querySelectorAll('h1').style.display = 'none';
  document.querySelector(divsion).style.display = 'block';
}
document.addEventListener('DOMContentLoaded', () => {
  document.querySelectorAll('button').forEach(button => {
    button.onclick = (e) => { // pass a parameter here
      //showPage(e.currentTarget.dataset.page); // get current target of event and its property.
      console.clear();
      console.log(e.currentTarget.dataset.page); // output on console
    }
  });
});
<!DOCTYPE html>
<html>

<head>
  <title>Show Page</title>

</head>

<body>
  <button data-page="page1">Page1</button>
  <button data-page="page2">Page2</button>
  <button data-page="page3">Page3</button>
  <h1 id="page1">This is page1</h1>
  <h1 id="page2">This is page2</h1>
  <h1 id="page3">This is page3</h1>
</body>

</html>

看看对你有没有帮助。