我在 Raphael Canvas 上自动创建了很多矩形,为简单起见,此代码仅使用两个:
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');
}
它创建了下面这个 block (如在 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 类指示要填充的颜色。我想使用单击功能单独更改每个矩形的类。我需要类似的东西:
function change_class() {
//something here
}
从我读到的所有内容来看,这是使用 .node
完成的,但这里我没有为每个 rect
提供单独的变量,因为 square
在 for()
循环的每次迭代中被覆盖。
实现此目的的一种方法是将所有矩形推送到一个数组,如下所示:
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);
}
然后我可以直接通过以下方式更改类(class):
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');
});
关于jquery - 拉斐尔节点选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6346762/