触发SVG元素上的Click事件 [英] Triggering a Click Event on an SVG element

查看:2409
本文介绍了触发SVG元素上的Click事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组svg节点,这些节点附有click事件侦听器.我还分配了nodeId来唯一标识我的不同节点

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);
}

我想做的是单击与svg组分开的按钮时调用此displayNodeInfo()函数.该函数应显示上一个节点或下一个节点,具体取决于单击的内容.我认为nodeId在这里会派上用场.

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
)};

我对D3还是很陌生,仍然想弄清它的本机方法,所以我只是想知道是否有人有类似的任务.非常感谢!

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!

推荐答案

我建议您使用节点索引为每个节点创建唯一的ID,并将其用于节点标识.应该跟踪当前所选节点的索引.

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).

这篇关于触发SVG元素上的Click事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆