简体   繁体   中英

How to add a click event or mouseover on dynamic elements ( enter/update/exit )?

based on this example: Need another help to show up text on the screen dynamically

it is possible to let elements (for example a text) in D3.js appear and disappear with the help of the enter/update/exit rule.

 var texts = svg.selectAll(".texts")
        .data(data);

    textsExit = texts.exit().remove();

    textsEnter = texts.enter()
        .append("text")
        .attr("class", "texts");

    textsUpdate = texts.merge(textsEnter).attr("x", 10)
        .attr("y", (d, i) => 20 + i * 16)
        .text((d,i) => "Node " + (i+1) + ", name: " + d.name);

Now i want to add a click event or a mouseover on the appearing text elements. So i tried to add a mouseover first and changed the textsUpdate part into:

     textsUpdate = texts.merge(textsEnter).attr("x", 10)
     .attr("y", (d, i) => 20 + i * 16)
      .text((d,i) => "Node " + (i+1) + ", name: " + d.name)
  .on("mouseover", function(d){ this.style.fill == "blue"});

The goal is that everytime when i move the mouse over the newly appereared elements, then they should turn blue. Unfortunally this did not worked well. Can someone help and give me a hint about the missing thing?

Thanks

You are stopping your access to textUpdate after you access .text(...) and before you access with .on(...). There is an extra semicolon before .on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM