对多个对象使用相同的 onmouseover 函数
我正在用 JavaScript 和 PHP 创建一个涉及网格的建筑游戏。网格中的每个方块都是一个 div,具有自己的 onmouseover 和 onmousedown 函数:
for(x=0; x < width; x++)
{
for(y=0; y < height; y++)
{
var div = document.createElement("div");
//...
div.onmouseclick = function() {blockClick(x, y)}
div.onmouseover = function() {blockMouseover(x, y)}
game.appendChild(div);
}
}
但是,所有方块似乎都具有最后添加的方块的 x 和 y。我可以理解为什么会发生这种情况 - 它是指向 x 和 y 的指针而不是克隆变量 - 但我该如何修复它呢?我什至尝试过
for(x=0; x < width; x++)
{
for(y=0; y < height; y++)
{
var div = document.createElement("div");
var myX = x;
var myY = y;
div.onmouseclick = function() {blockClick(myX, myY)}
div.onmouseover = function() {blockMouseover(myX, myY)}
game.appendChild(div);
}
}
同样的结果。
我使用的是 div.setAttribute("onmouseover", ...)
,它在 Firefox 中有效,但在 IE 中无效。 谢谢!
I'm creating a building game in JavaScript and PHP that involves a grid. Each square in the grid is a div, with an own onmouseover and onmousedown function:
for(x=0; x < width; x++)
{
for(y=0; y < height; y++)
{
var div = document.createElement("div");
//...
div.onmouseclick = function() {blockClick(x, y)}
div.onmouseover = function() {blockMouseover(x, y)}
game.appendChild(div);
}
}
But, all of the squares seem to have the x and y of the last square that was added. I can sort of see why this is happening - it is making a pointer to x and y instead of cloning the variables - but how could I fix it? I even tried
for(x=0; x < width; x++)
{
for(y=0; y < height; y++)
{
var div = document.createElement("div");
var myX = x;
var myY = y;
div.onmouseclick = function() {blockClick(myX, myY)}
div.onmouseover = function() {blockMouseover(myX, myY)}
game.appendChild(div);
}
}
with the same result.
I was using div.setAttribute("onmouseover", ...)
which worked in Firefox, but not IE.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要创建一个闭包来保留
x
和y
的值。这应该可以解决问题:一种更简洁的方法是定义一个函数来创建 div,然后在每次迭代时调用它:
You need to create a closure to retain the value of
x
andy
. This should do the trick :A cleaner way of doing this is to define a function to create the div and then call it at each iteration :
这是因为由于周围的闭包,您实际上在每个处理程序之间共享相同的变量。所以你需要像这样创建本地闭包:
That is because you are actually sharing the same variables across each handler because of the surrounding closure. So you need to create local closures like this: