Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
132 views
in Technique[技术] by (71.8m points)

javascript - D3 on("click", toggle

Two of my nodes representing power supply objects. I added an .on("click"..) event on the power-plug node, which changes the colour from green to red. I want to switch the colour from the battery node to green as soon as the power-plug is red. I struggle with a proper toggle function so far.

enter image description here

enter image description here

function toggleColor() {
if (!toggle) {
    d3.select(this).style("fill", "red")
    toggle = true
} else if (toggle) {
    d3.select(this).style("fill", "lightgreen")
    toggle = false
}

}

// set node attributes for node:usv
node
    .filter((d) => {
        return (d.name == "usv")
    })
    .style("fill", "yellow")

// set node attributes for node:power-plug
node
    .filter((d) => {
        return (d.name == "power-plug")
    })
    .style("fill", "lightgreen")
    .on("click", toggleColor)

I just can′t get the connection working as I am using (this) as a pointer. Any idea?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I managed. My filter query was faulty.

function toggleColor() {
if (!toggle) {
    d3.select(this).style("fill", "red")
    d3.selectAll("circle")
        .filter(function(d) {
            return d.name == "usv"
        }).style("fill", "lightgreen")
    toggle = true           
} else if (toggle) {
    d3.select(this).style("fill", "lightgreen")
    d3.selectAll("circle")
        .filter(function(d) {
            return d.name == "usv"
        }).style("fill", "yellow")
    toggle = false
}

}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...