我在Raphael画布上自动创建了很多rects,为简单起见,这段代码只使用了两个:
for (i = 0; i < 2; ++i) {
var square = paper.rect(0 + 100*i, 0, 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
}
从我读过的所有内容来看,这都是使用.node
完成的,但是在这里我没有为每个rect
设置单独的变量,因为每次迭代都会覆盖square
for()
循环。
执行此操作的一种方法是将所有rects推送到数组,如下所示:
squares = [];
for (i = 0; i < 2; ++i) {
var square = paper.rect(0 + 100*i, 0, 70, 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方法是什么?
提前致谢, 阿德里安
答案 0 :(得分:2)
如果你想单击框本身来改变它的颜色,你不需要jQuery,你可以使用Raphael的内置事件方法,并将矩形称为this
,如下所示:
rect.click( function () {
this.node.setAttribute('class', 'newClass');
});