gpt4 book ai didi

javascript - 如果条件从未满足,因此简单条形图中的条形始终为蓝色,而我希望它们对于低于特定数字的值为红色

转载 作者:行者123 更新时间:2023-12-02 21:32:28 24 4
gpt4 key购买 nike

我一直在尝试使用这段代码来创建具有给定数据的条形图。它有效,但它永远不会返回红色,而是始终返回蓝色。我尝试过将 b[i]>0,但仍然只有蓝色条。带参数 b 的函数肯定会执行,我也尝试过 (b,i) 。

<!DOCTYPE html>
<html>
<head>
<script src = "https://d3js.org/d3.v5.min.js"></script>
</head>
<body>
<svg height = "250px" width="500px"></svg>
<script>
var b = [5,9,6,4,3];
var x = 100;
const height = 250;
for(var i=0; i<b.length;i++)
{
var svg = d3.select("svg").data(b).append("rect").attr("x",x)
.attr("y",height - (b[i]*20))
.attr("width",20).attr("height", b[i]*20).attr("fill", function(b){
if(b[i]<6) //This if condition never gets checked and hence doesn't work
{
return "red";
}
else
{
return "blue"; //This executes
}
})
x = x + 25; //Increment for the position of next bar
}
</script>
</body>
</html>

最佳答案

你创建了一个影子变量b,作为回调的参数,所以它不是一个数组,而是它的项目。由于您使用循环来分别绘制每个点,因此您可以避免使用回调。所以而不是

.attr("fill", function(b) { ... })

你需要写这个

.attr("fill", b[i] < 6 ? "red" : "blue")

顺便说一句,d3 js 可以为你迭代点:

<script>
var b = [5, 9, 6, 4, 3];
var xOffset = 100;
const height = 250;

var svg = d3.select("svg")
.selectAll('rect')
.data(b)
.enter()
.append('rect')
.attr("x", (d, i) => xOffset + 25 * i)
.attr("y", d => height - d * 20)
.attr("width", 20)
.attr("height", d => d * 20)
.attr("fill", d => d < 6 ? "red" : "blue");
</script>

关于javascript - 如果条件从未满足,因此简单条形图中的条形始终为蓝色,而我希望它们对于低于特定数字的值为红色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60585636/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com