如何在将数组的每个值分配给DOM中的所有svg的同时一遍又一遍地迭代数组

How can I iterate through an array over and over again while assigning each of its values to all the svgs in my DOM

本文关键字:一遍 数组 svg 迭代 DOM 分配      更新时间:2023-09-26

如果我的问题措辞不好,很抱歉。我是个初学者,不知道事物的正确标签。

我正在用d3.js制作一张日本地图,并想为每个都道府县指定一种颜色。每个县都有自己的svg。我有一个我想使用的颜色的十六进制值的数组,基本上我想写一个函数,将数组的第一种颜色分配给第一个svg的"fill"属性,第二种分配给第二个svg,依此类推。颜色在某个时候必须重复,因为有太多的县。我真的很难构思如何去做这件事,我很乐意得到任何帮助!我的代码在下面。我想代码应该放在javascript的底部,我有?议论

此外,这方面的基础来自Mike Bostock的"让我们制作地图"教程(如果有帮助的话)。

<!DOCTYPE html>
<head>
<meta charset="utf-8">
<style>

</style>
</head>
<body>
<script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script src="//d3js.org/topojson.v1.min.js"></script>
<script>
var width = 960;
var height = 1160;
/* list of colors to iterate thru for prefecture color */
var colors = ["#8dd3c7", "#ffffb3", "#bebada", "#fb8072", "#80b1d3",
              "#fdb462", "#b3de69", "#fccde5", "#d9d9d9"];
var projection = d3.geo.mercator()
    .center([138.3, 39.2])
    .scale(1500);
var path = d3.geo.path()
    .projection(projection);
var svg = d3.select("body").append("svg")
    .attr("height", height)
    .attr("width", width);
/* draws the map. try to make a loop in here which uses the data id of
    the prefectures to uses the color list above to differentiate pref*/
d3.json("japanv2.json", function(error, japan) {
  svg.selectAll(".prefecture")
      .data(topojson.feature(japan, japan.objects.prefectures).features)
    .enter().append("path")
      .attr("class", function (d) { return "prefecture " + d.id; })
      .attr("d", path)
/*?*/ .attr("fill", 
      }
});

</script>
</body>
</html>

将其放入属性中:

.attr("fill", function(d,i){
    return colors[i%colors.length]
});

这个片段的作用是什么

首先,function(d,i)中的i返回每个路径的索引。所以,如果你这样做:

.attr("fill", function(d,i){
    console.log(i);
    return colors[i%colors.length];
});

你会在你的控制台上看到一堆数字。假设您有200条路径,那么i将从0变为199。

现在是模运算符:

x % y

它返回除法的余数。所以,假设你的colors是一个有9种颜色的阵列,这个:

i % colors.length

将返回此序列:

0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 1 etc

可以用来获取colors值。

附言:在地图中,任何地图中,我们只需要4种颜色就可以避免任何两个颜色相同的区域有共同的边界!(难以置信,我知道…)

我以前从未使用过D3,但跟踪您在数组中的位置还不错。

首先,我将使用另一个变量跟踪您在数组中的位置,该变量可能设置在var colors行下。

var currentColor = 0;

然后,当您更改地区颜色时,您可以使用引用阵列中的当前位置

colors[currentColor]

完成此操作后,您将希望使用以下内容更新当前颜色:

currentColor++;
if (currentColor == colors.length) {
    currentColor = 0;
}

这会增加currentColor值+1,然后在使用最后一种颜色后将其重置回0。这样,如果你有更多的县,你可以使用从头开始的颜色。

更新

仔细查看您的代码,我想我在回答中提到的colors[currentColor]会在这一行的逗号后面:

/*?*/ .attr("fill",