尝试通过抓取当前路径的 pathID 并将其分配为构成stroke-width: 2px
的 class .highlight 来突出显示当前路径行。
console.log显示当前路径ID ,但它不想分配一个类。请帮忙。我在这里做错了什么?
//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);
}
答案 0 :(得分:3)
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
是绑定到路径的mouseover
事件,导致d3.select(this)
作为路径本身,因此您不需要任何路径.select(path#pathID)
在这种情况下,但是d3.select(this).classed('highlighted', true)
答案 1 :(得分:0)
尝试一下:
function highlightPath(d) {
let pathID = d3.select(this).attr("id");
console.log(pathID);
d3.select("path#" + pathID)
.attr("class", "highlight");
}