use*_*597 0 html javascript css
我有这两个javascript函数可以更改背景并显示和隐藏字段,但是每个按钮只能运行一次
function showabout(){
hidecontact = document.getElementById("contactus");
hidecontact.style.display = "none";
hide.style.backgroundImage = "url(aboutus.jpg)";
showabout = document.getElementById("aboutus");
showabout.style.display = "inline";
showabout.style.cssFloat = "left";
secbuttons.style.paddingLeft = "670px";
}
function showcontact(){
hideabout = document.getElementById("aboutus");
hideabout.style.display = "none";
hide.style.backgroundImage = "url(contact.jpg)";
showcontact = document.getElementById("contactus");
showcontact.style.display = "inline";
showcontact.style.cssFloat = "left";
secbuttons.style.paddingLeft = "670px";
}
<font color="#33FF66"><h2 style="cursor:pointer" onmouseover = "showabout()"> </h2></font>
<font color="#33FF66"><h2 style="cursor:pointer" onclick="showcontact()"> </h2></font><br />
<font color="#33FF66"><h2 style="cursor:pointer" onmouseover = "showcontact()"> </h2></font>
Run Code Online (Sandbox Code Playgroud)
三个H2是导致错误的线.它说"未捕获类型错误,对象不是函数".
您的问题是您正在重新定义showabout和showcontact- 您的函数 - 引用HTML元素.
这两个代码片段:
function showabout() {
...
}
Run Code Online (Sandbox Code Playgroud)
和
showabout = document.getElementById("aboutus");
Run Code Online (Sandbox Code Playgroud)
都设置变量window.showabout.第一个为函数分配函数window.showabout,后者为其分配一个HTML元素window.showabout.
因为您不使用var关键字来声明函数中的变量,所以showabout = document.getElementById("aboutus")重新分配showcontact以引用该元素而不是您定义的函数.那么当你尝试showcontact()第二次调用时,它不起作用,因为showcontact它不再是一个函数.
在您编写JavaScript时,简单的修复实际上是一个全面的规则:
这里还有第二个教训:
虽然如果你只showabout提前声明变量,你的代码就会起作用,但读起来仍然会让人感到困惑.它显示的函数和元素应该有不同的名称.比如说,调用showAboutBox它显示的功能和框aboutBox.这样就没有任何混淆的余地 - 无论是你还是语言 - 关于你所指的是什么.
| 归档时间: |
|
| 查看次数: |
2639 次 |
| 最近记录: |