[英]Simple javascript function undefined error
Simply put, I keep getting a Uncaught ReferenceError stating openSideBar is not defined. 简而言之,我不断收到Uncaught ReferenceError,指出未定义openSideBar。 I cannot figure out why. 我不知道为什么。
<head>
<script>
document.getElementById('openSideBarButton').addEventListener ("click", openSideBar);
function openSideBar() {
document.getElementById('sideBar').style.width "100%";
}
function closeSideBar() {
document.getElementById('sideBar').style.width "0%";
}
</script>
</head>
Your script is in the <head>
section of the page and attempts to document.getElementById('openSideBarButton')
, but that element doesn't exist that early in the page. 您的脚本位于页面的<head>
部分,并尝试document.getElementById('openSideBarButton')
,但是该元素在页面的早期并不存在。
Move your script somewhere on the page after the button so that the button exists before your script runs. 在按钮之后将脚本移动到页面上的某个位置,以便该按钮在脚本运行之前就存在。
Side note: You are also missing equals signs in each of your functions. 旁注:您还缺少每个功能中的等号。
Working version: 工作版本:
<script>
document.getElementById('openSideBarButton').addEventListener ("click", openSideBar);
function openSideBar() {
document.getElementById('sideBar').style.width = "100%";
}
function closeSideBar() {
document.getElementById('sideBar').style.width = "0%";
}
</script>
</body>
Notice that it is right before the closing </body>
tag instead of in the head section of the page. 请注意,它恰好在结束</body>
标记之前,而不是在页面的头部。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.