Javascript 将参数传递给Raphael.js中的.mouseover函数
我在一个节点数组上有一个循环,我试图在屏幕上显示每个节点的名称,作为一些Raphael元素的工具提示 这是我的密码:Javascript 将参数传递给Raphael.js中的.mouseover函数,javascript,raphael,Javascript,Raphael,我在一个节点数组上有一个循环,我试图在屏幕上显示每个节点的名称,作为一些Raphael元素的工具提示 这是我的密码: for(var i=0; i<nodes.length; i++){ paper.rect(nodes[i].getX(), nodes[i].getY(), nodes[i].width, nodes[i].getHeight()) .attr({fill:nodes[i].getColor(), "fill-opacity": 1}
for(var i=0; i<nodes.length; i++){
paper.rect(nodes[i].getX(), nodes[i].getY(), nodes[i].width, nodes[i].getHeight())
.attr({fill:nodes[i].getColor(), "fill-opacity": 1}).mouseover(function () {
this.animate({"fill-opacity": .4}, 500);
this.attr({title:nodes[i].name});
}).mouseout(function () {
this.animate({"fill-opacity": 1}, 500);
}).drag(move, dragstart, dragend);
}
for(var i=0;i事件处理程序中的作用域更改。尝试在for循环外部声明和定义节点以及mouseover/out函数。然后使用鼠标事件的函数名:。mouseover(myFunctionDefinedOutsideForloop)
循环完成后,将调用您的mouseover
函数,因此i
不再存在。一个简单而灵活的解决方案是利用Raphael的data()
方法来存储您需要的内容:
paper.rect(nodes[i].getX(), nodes[i].getY(), nodes[i].width, nodes[i].getHeight())
.attr({fill:nodes[i].getColor(), "fill-opacity": 1})
.data({"title": nodes[i].name})
.mouseover(function () {
this.animate({"fill-opacity": .4}, 500);
this.attr({title: this.data("title") });
}).mouseout(function () {
...
当然,您可以根据自己的喜好进行更改:
.data({"index": i})
...
this.attr({title: nodes[this.data("index")].name });
或者,如果需要多个属性,只需存储整个对象本身
.data({"node": nodes[i]})
...
this.attr({title: this.data("node").name });
所有这些都归结为最适合您的目的的东西。这里有一个javascript技巧,通过闭包将其他东西传递给事件处理程序/回调:
paper.rect(nodes[i].getX(), nodes[i].getY(), nodes[i].width, nodes[i].getHeight())
.attr({fill:nodes[i].getColor(), "fill-opacity": 1})
.data({"title": nodes[i].name})
.mouseover(handleMouseOver(dataYouWant))
.mouseout(function () {
...
function handleMouseOver(dataYouWant) {
return function(){
// use dataYouWant in your code
this.animate({"fill-opacity": .4}, 500);
this.attr({title: this.data("title") });
}
}
paper.rect(nodes[i].getX(), nodes[i].getY(), nodes[i].width, nodes[i].getHeight())
.attr({fill:nodes[i].getColor(), "fill-opacity": 1})
.data({"title": nodes[i].name})
.mouseover(handleMouseOver(dataYouWant))
.mouseout(function () {
...
function handleMouseOver(dataYouWant) {
return function(){
// use dataYouWant in your code
this.animate({"fill-opacity": .4}, 500);
this.attr({title: this.data("title") });
}
}