我一直在尝试使用this
关键字来获取a,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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句