In creating a two.js object, here are the parts: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()); });我试图将所有必需的参数保存在数组中,如下所示:I tried to save all the necessary parameters in an array as such: [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引起的,该设置应该是每个循环和迭代.require a fresh variable every time it is fired thus the output is a group of circles that when clicked individually, only the last one changes color because of the setting that I have which is caused by var rotato that should be new every circle and iteration.如何使变量动态化,或者有更好的解决方案?How do I make the variable dynamic or is there a better solution to this mess? 这是一个Codepen叉.推荐答案此处的问题是JavaScript的for语句不会为每次迭代创建闭包.结果,当单击任何圆圈时,它将查找对rotato的引用.该变量将在每次迭代中重用,其结果就是您所指的数组中的 last 项.The issue here is that JavaScript's for statement doesn't create closures for each iteration. As a result when any of the circles is clicked it looks for what the reference to rotato. This variable is reused for each iteration and the result is what you're referring to as the last item in the array.我分叉并制作了一个新的Codepen,它使用了 underscore.js 的map方法在two.js中.这类似于for语句,不同之处在于,每次迭代都会创建闭包对要构造的每个rotato变量进行独立引用.I've forked and made a new codepen that uses underscore.js's map method which is bundled in two.js. This is similar to a for statement except that for each iteration it creates a closure making independent references to each of the rotato variables you're constructing. http://codepen.io/anon/pen/ylzvx 这篇关于创建动态Two.js变量以涉及单个单击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-29 10:46