atr onmouseover到一个for循环中创建的Raphaël.js变量

时间:2012-11-10 11:51:06

标签: javascript html for-loop raphael onmouseover

希望有人能提供帮助。

我从svg文件中获得了大量的路径(这里只显示了几个),我存储在一个数组中,以便在Raphael纸上动态创建它们。

var paths = "M539.99,181v95.141h-0.12L509.521,181H539.99zdivideM539.99,276.511v84.85h-30.41L539.99,276.511zdivideM539.99,85.021V181h-30.47L539.99,85.021"; // string with paths from svg file. Much much bigger in real code
var pathsArray = paths.split("divide"); // putting all paths in an array 

一切正常,直到我尝试将一个属性分配给for循环内的onmouseover函数中的路径。什么都没发生。并且控制台中没有错误消息。

var currentPath = window['section' + i];
currentPath.node.onmouseover = function() {  
    this.style.cursor = 'pointer'; 
    currentPath.attr("fill", "#ccc"); // <-- THIS PART DOESNT WORK
}

我也是这样试过的:

window['section' + i].attr("fill", "#ccc");

给我一​​个错误信息: TypeError:'undefined'不是对象(评估'window ['section'+ i] .attr')

以下是完整代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="jquery-1.8.2.js"></script>
<script type="text/javascript" src="raphael.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
</head>

<body>

<script type="text/javascript">

var paths = "M539.99,181v95.141h-0.12L509.521,181H539.99zdivideM539.99,276.511v84.85h-30.41L539.99,276.511zdivideM539.99,85.021V181h-30.47L539.99,85.021"; // string with paths from svg file. Much much bigger in real code
var pathsArray = paths.split("divide"); // putting all paths in an array 

var paper = Raphael(10, 50, 1000, 1000);

for (var i=0;i<pathsArray.length;i++)
{ 

var currentPath = window['section' + i];

currentPath = paper.path(pathsArray[i]);
currentPath.attr("fill", "#f00");
currentPath.attr("stroke", "#fff");
currentPath.node.onmouseover = function() {  
    this.style.cursor = 'pointer'; 
    currentPath.attr("fill", "#ccc"); // <-- THIS PART DOESNT WORK
}

}

</script>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

尝试使用关键字,同样根据documentation,内置鼠标悬停事件。所以以下内容也应该有效:

currentPath.mouseover(function() {  
    this.node.style.cursor = 'pointer';  // using 'node' property to get access to DOM element
    this.attr("fill", "#ccc"); // 'this' should refer to Raphael element
});

即使currentPath在处理函数内部,它总是在循环中获取最后一个'currentPath'的值。