问题描述
|
我在Raphael画布上自动创建了许多rect,为简单起见,此代码仅使用两个:
for (i = 0; i < 2; ++i) {
var square = paper.rect(0 + 100*i,70,70);
square.node.setAttribute(\'id\',\'_\' + i);
square.node.setAttribute(\'class\',\'foo\');
}
会在下面创建此块(如Firefox中的视图选择源所示):
<svg height=\"560\" width=\"560\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\"><desc>Created with Raphael</desc><defs></defs><rect class=\"foo\" id=\"_0\" stroke=\"#000\" fill=\"none\" ry=\"0\" rx=\"0\" r=\"0\" height=\"70\" width=\"70\" y=\"0\" x=\"0\"></rect><rect class=\"foo\" id=\"_1\" stroke=\"#000\" fill=\"none\" ry=\"0\" rx=\"0\" r=\"0\" height=\"70\" width=\"70\" y=\"0\" x=\"100\"></rect></path></svg>
css类指示要填充的颜色。我想使用click函数分别更改每个rect的类。我需要类似的东西:
function change_class() {
//something here
}
从我已经阅读的所有内容中,这是使用ѭ3done完成的,但是在这里,对于每个ѭ4each我都没有单独的变量,因为在each6ѭ循环的每次迭代中都覆盖了square
。
一种方法是将所有矩形推入数组,如下所示:
squares = [];
for (i = 0; i < 2; ++i) {
var square = paper.rect(0 + 100*i,70);
square.node.idx = i;
square.node.setAttribute(\'class\',\'foo\');
squares.push(square);
}
然后,我可以通过以下方式直接更改类:
squares[0].node.setAttribute(\'class\',\'other\');
但是...我仍然不知道如何通过通用功能change_class()
来实现...我需要类似的东西:
$(\'rect\').click(function() {
change_class(); // the click function should pass \"$(this)\" to change_class ?
});
什么是正确的jQuery + Raphael方法来做到这一点?
提前致谢,
阿德里安
解决方法
如果要单击框本身来更改其颜色,则不需要jQuery,可以使用Raphael的内置事件方法,并将矩形称为
this
,如下所示:
rect.click( function () {
this.node.setAttribute(\'class\',\'newClass\');
});