我正在尝试在HTML文档中添加副本。旁白应该像内联脚注。当读者将鼠标放在子弹上时,会显示旁边的全文。当读者将鼠标移开时,文本会再次隐藏。我正在尽量减少使其工作所需的HTML数量,因此我使用的是<span class="aside"...
而不是<span onmousover="showAside();"...
无论如何,我对Javascript还是比较陌生的,而且我遇到了一些我似乎无法弄清楚的新手错误。当我在浏览器中加载下面的测试用例时,旁边的文本会被预期的子弹替换。但是,当我鼠标悬停或弹出子弹时,我收到错误“this.element is undefined”。但它是在类原型中定义的!是什么给了什么?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/ecmascript">
<!--
var asides = [];
// object prototype
function Aside(aside_element)
{
this.element = aside_element;
this.text = this.element.innerHTML;
this.element.onmouseover = this.show;
this.element.onmouseout = this.hide;
this.hide();
}
Aside.prototype.hide = function()
{
this.element.innerHTML = "•";
}
Aside.prototype.show = function()
{
this.element.innerHTML = this.text;
}
// get all <span> elements of class "aside"
function make_asides()
{
span_elements = document.getElementsByTagName("span");
for ( var i = 0, len = span_elements.length; i < len, span_element = span_elements[i]; ++i )
{
if ( span_element.className == "aside" )
asides.push(new Aside(span_element));
}
return asides;
}
// initialize script
window.onload = function()
{
make_asides();
}
-->
</script>
<title>Test Case</title>
</head>
<body>
<p>Hover over the bullet and see the magic text! <span class="aside">This is the magic text.</span></p>
</body>
</html>
答案 0 :(得分:5)
因为范围错误,您需要使用闭包
var that = this;
this.element.onmouseover = function(){ that.show(); };
this.element.onmouseout = function(){ that.hide(); };