提问者:小点点

JavaCIPT中未捕获的TypeError


我一直在尝试使用this关键字来获取数据集,但我一直得到uncapted TypeError:无法读取未定义的属性'page',在下面的脚本中,我试图实现的是,每当单击按钮时,它显示某些内容并隐藏所有其他内容

<!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>

共2个答案

匿名用户

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

null

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>

匿名用户

如果使用箭头函数,则将不包含当前元素,则需要在函数中传递一个参数(事件),获取其当前目标,然后获取属性。

null

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>