[英]Why this mouseover script doesn't work properly?
I have written this script: 我写了这个脚本:
var elms = document.getElementsByTagName('li');
for (var i = 0; i < elms.length; i++){
if (elms[i].className == 'liitem'){
var delete_id = elms[i].id;
elms[i].onmouseover = function(){
document.getElementById("delete-" + delete_id).style.display = "block";
}
elms[i].onmouseout = function(){
document.getElementById("delete-" + delete_id).style.display = "none";
}
}
}
HTML: HTML:
<li class="liitem" id="205">
<span>
<a href="http://www.google.com/finance/portfolio?action=view&pid=1" target="_blank">One:</a> </span>
<br>
<ul><li>
<span><a href="http://www.google.com" target="_blank">www.google.com</a> </span><span id="delete-205" style="float:right;font-size:11px;display:none;"><a href="">delete</a></span></li></ul>
</li><br>
<li class="liitem" id="204">
<span>
<a href="http://www.google.com/finance/portfolio?action=view&pid=1" target="_blank">Two:</a> </span>
<br>
<ul><li>
<span><a href="http://www.google.com" target="_blank">www.google.com</a> </span><span id="delete-204" style="float:right;font-size:11px;display:none;"><a href="">delete</a></span></li></ul>
</li><br>
<li class="liitem" id="203">
<span>
<a href="http://www.google.com/finance/portfolio?action=view&pid=1" target="_blank">Three:</a> </span>
<br>
<ul><li>
<span><a href="http://www.google.com" target="_blank">www.google.com</a> </span><span id="delete-203" style="float:right;font-size:11px;display:none;"><a href="">delete</a></span></li></ul>
</li><br>
Live demo: http://jsfiddle.net/5FBjm/1/ 现场演示: http : //jsfiddle.net/5FBjm/1/
but it doesn't work properly. 但它不能正常工作。 I want that when there is mouseover on a certain <li>
element of "liitem" class, then show "delete" link of that element (with the same ID). 我希望当“ liitem”类的某个<li>
元素上有鼠标悬停时,然后显示该元素的“ delete”链接(具有相同的ID)。
In my script instead, appear only the last "delete". 相反,在我的脚本中,仅显示最后一个“删除”。 Why? 为什么?
使用this.id
替换delete_id
使用: http : //jsfiddle.net/5FBjm/4/
You have a variable scope problem - in the callbacks delete_id
always has the last value assigned, not the value it had when the callback was registered. 您有一个变量范围问题-在回调中, delete_id
始终分配有最后一个值,而不是在注册回调时具有的值。
Do a Google search for "javascript loop scope callback" for hundreds of examples (many of them here) on how to fix it. 在Google上搜索“ javascript循环作用域回调”,以获取数百个有关如何修复它的示例(此处有很多示例)。
EDIT - as @gabitzish points out, you can just use this.id
编辑-正如@gabitzish指出的,您可以只使用this.id
This only works because the browser passes the current element as this
to the callback. 这只能是因为浏览器将当前元素作为this
回调。
Since the loop variable you need is actually that element's id
, you can just use it directly and not worry about the loop scope problem. 由于您需要的循环变量实际上是该元素的id
,因此您可以直接使用它,而不必担心循环范围问题。 The answer above would apply if it been some other variable which isn't a property of the element. 如果它是不是元素属性的其他变量,则上述答案适用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.