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

console.log显示当前的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是绑定到路径的mouseover事件,导致
  d3.select(this)成为路径本身,因此您不需要任何路径
  在这种情况下.select(path#pathID)
  d3.select(this).classed('highlighted', true)

09-12 15:03