Triggering a Click Event on an SVG element

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-24 14:02:12

问题


I have a group of svg nodes that have a click event listener attached to them. I also assign a nodeId to uniquely identify my different nodes

var nodeId = 0;
nodeGroup.append("svg:circle")
    .attr("r", 7)
    .style("fill", "blue")
    .style("stroke", "orange")
    .attr("data-node-id", function(d,i) {
          return nodeId += 1;
     })
    .on('click', nodeInfo);

On click, the node triggers a function to display the node object

var nodeInfo = function displayNodeInfo(node){
    console.log(node);
}

What I am trying to do is invoke this displayNodeInfo() function on click of a button separate from the svg group. The function should display either the previous or the next node depending on what was clicked. I figure that nodeId would come in handy here.

<button id="next-node" />
<button id="previous-node" />

$("#next-node").on("click", function(e){
    displayNodeInfo() //Not sure how to pass the next node here
)};

I'm fairly new to D3 and still figuring out its native methods, so I'm just wondering if anyone's had a similar task. Thanks much!


回答1:


I would suggest you to use node index for creating unique id for each node and use the the same for node identification. Should track the index of the present selected node.

var activeNodeIndex = 0;

nodeGroup.append("svg:circle")
    .attr("r", 7)
    .style("fill", "blue")
    .style("stroke", "orange")
    .attr("id", function(d,i) {
          return "node"+i; //i has value from 0 to (No. of nodes - 1)
     })
    .on('click', function(node,i){
       activeNodeIndex = i; //Track present selected node.
       displayNodeInfo(node);
    });

function displayNodeInfo(node){
    console.log(node);
}

$("#next-node").on("click", function(e){
   var nextNode  = d3.select("#node"+(activeNodeIndex +1)); //find next node using index
   displayNodeInfo(nextNode);
)};

$("#prev-node").on("click", function(e){    
    var prevNode  = d3.select("#node"+(activeNodeIndex-1));  //find previous node using index
    displayNodeInfo(prevNode);
)};

Note: Enable/disable Next/Prev buttons based on the current node selection(1st OR last).



来源:https://stackoverflow.com/questions/35007718/triggering-a-click-event-on-an-svg-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!