我已经摆弄了一段时间,但它不起作用,我也不知道为什么。请帮忙。这是我所拥有的:
<html>
<head>
<title>lala</title>
</head>
<body>
<h1 onmouseover="go('The dog is in its shed')" onmouseout="clear()">lalala</h1>
<div id="goy"></div>
<script type="text/javascript">
function go(what) {
document.getElementById("goy").innerHTML = what;
}
function clear() {
document.getElementById("goy").innerHTML = "";
}
</script>
</body>
</html>
鼠标悬停有效并在 div 中显示文本,但是当我将鼠标移出 h1 标签时,文本停留在那里,我不知道为什么,帮助将不胜感激。
最佳答案
问题似乎是全局符号 clear
已在使用中,您的函数无法成功覆盖它。如果您将该名称更改为其他名称(我使用了 blah
),它就可以正常工作:
直播:Version using clear
which fails | Version using blah
which works
<html>
<head>
<title>lala</title>
</head>
<body>
<h1 onmouseover="go('The dog is in its shed')" onmouseout="blah()">lalala</h1>
<div id="goy"></div>
<script type="text/javascript">
function go(what) {
document.getElementById("goy").innerHTML = what;
}
function blah() {
document.getElementById("goy").innerHTML = "";
}
</script>
</body>
</html>
这很好地说明了基本原则:尽可能避免使用全局变量。浏览器中的全局命名空间难以置信拥挤,当发生冲突时,您会遇到像这样的奇怪错误。
一个推论是不要使用旧式 onxyz=...
属性来连接事件处理程序,因为它们需要全局变量。相反,至少使用代码来连接:Live Copy
<html>
<head>
<title>lala</title>
</head>
<body>
<h1 id="the-header">lalala</h1>
<div id="goy"></div>
<script type="text/javascript">
// Scoping function makes the declarations within
// it *not* globals
(function(){
var header = document.getElementById("the-header");
header.onmouseover = function() {
go('The dog is in its shed');
};
header.onmouseout = clear;
function go(what) {
document.getElementById("goy").innerHTML = what;
}
function clear() {
document.getElementById("goy").innerHTML = "";
}
})();
</script>
</body>
</html>
...甚至更好的是,使用 DOM2 的 addEventListener
(或 IE8 及更早版本的 attachEvent
),这样您就可以为一个元素上的事件设置多个处理程序。
关于javascript - 如何清除内部 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22593759/