gpt4 book ai didi

javascript - d3 无法读取未定义的属性 'classed'

转载 作者:行者123 更新时间:2023-11-29 18:46:41 32 4
gpt4 key购买 nike

尝试通过获取当前路径的 pathID 并为其分配一个 class .highlight 来突出显示当前路径线,使 stroke-width: 2px

console.log 显示current pathID 但它不想分配一个类。请帮忙。我在这里做错了什么?

Codepen

//Generate group (main)
let groups = svg.selectAll("g")
.data(dataset)
.enter()
.append("g")
.on("mouseover", function(d) {
d3.select(this)
.call(revealCityName)
})
.on("mouseout", hideCityName)

//Path (path #, path line)
groups
.append("path").classed("line", true)
.attr("id", function(d) {
console.log(d.country)
if (d && d.length != 0) {
return d.country.replace(/ |,|\./g, '_');
}
})
.attr("d", d => line(d.emissions))
.classed("unfocused", true)
.style("stroke-width", d =>
d.country === "China" ? 1 : 0.2
)
.on("mouseover", highlightPath);

//Text (contries on the left y axis)
groups
.append("text")
.datum(function(d) {
return { country: d.country, value: d.emissions[d.emissions.length - 1]};
})
.attr("transform", function(d) {
if (d.value) {
return "translate(" + xScale(d.value.year) + "," + yScale(d.value.amount) + ")";
} else {
return null;
}
})
.attr("x", 3)
.attr("dy", 4)
.style("font-size", 10)
.style("font-family", "Abril Fatface")
.text(d => d.country)
.classed("hidden", function(d) {
if (d.value && d.value.amount > 700000) {
return false
} else {
return true;
}
})

还有一个我正在尝试分配类的函数:

    function highlightPath(d) {

let pathID = d3.select(this).attr("id");

console.log(pathID);

let currentId = d3.select(this).select("path#" + pathID)
console.log("Current ID: ",currentId)
.classed("highlight", true);
}

最佳答案

console.log 正在拆分代码。这是错误:

function highlightPath(d) {

let pathID = d3.select(this).attr("id");

console.log(pathID);

let currentId = d3.select(this).select("path#" + pathID)
console.log("Current ID: ",currentId) /* <<<<<<<<< HERE (line 218 in your codepen) */
.classed("highlight", true);
}

应该是:

function highlightPath(d) {

let pathID = d3.select(this).attr("id");

console.log(pathID);

let currentId = d3.select(this).classed('highlight', true) // thanks to @shashank

console.log("Current ID: ", currentId)
}

更新演示:https://codepen.io/anon/pen/qQRJXp

@Shashank 评论后更新

highlightPath is a mouseover event bound to the path which results in d3.select(this) to be the path itself and so you won't need any .select(path#pathID) in this case but just d3.select(this).classed('highlighted', true)

关于javascript - d3 无法读取未定义的属性 'classed',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53287312/

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