问题
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