在创建two.js对象时,以下是部分:
var circle1 = two.makeCircle(676,326,25);
circle1.noStroke().fill = getRandomColor();
circle1.domElement = document.querySelector('#two-' + circle1.id);
$(circle1.domElement)
.css('cursor', 'pointer')
.click(function(e) {
circle1.fill = getNonMainRandomColor(getRandomColor());
});我试图将所有必要的参数保存在这样的数组中:
[x position, y position, radius, color]
所以我有这个功能
function showCircles(array) {
for(var i = 0; i < array.length; i++) {
var rotato = two.makeCircle(array[i][0],array[i][1],array[i][2]);
rotato.noStroke().fill = array[i][3];
rotato.domElement = document.querySelector('#two-' + rotato.id);
$(rotato.domElement).css('cursor', 'pointer').click(function(e) {rotato.fill = getNonMainRandomColor(getRandomColor());});
}
}后者的问题在于
rotato.domElement = document.querySelector('#two-' + rotato.id);
$(rotato.domElement).css('cursor', 'pointer').click(function(e) {rotato.fill = getNonMainRandomColor(getRandomColor());});每次触发时都需要一个新的变量,因此输出是一组圆圈,当单独单击时,只有最后一个变量会改变颜色,因为我拥有的设置是由var rotato引起的,应该是新的每一个循环和迭代。
如何使变量动态,或者是否有更好的解决方案来解决这一混乱?
这是一个密码叉。
发布于 2013-10-18 19:26:43
这里的问题是JavaScript的for语句不会为每次迭代创建闭包。因此,当单击任何一个圆圈时,它都会查找对rotato的引用。每个迭代都重用这个变量,结果就是数组中的最后一项。
我使用underscore.js的map方法(捆绑在two.js中)进行了分叉,并制作了一个新的代码页,这类似于for语句,只不过在每次迭代时,它都创建了一个闭锁,对正在构建的每个rotato变量进行独立引用。
http://codepen.io/anon/pen/ylzvx
https://stackoverflow.com/questions/19357533
复制相似问题