简体   繁体   English

在d3中选择动态DOM元素

[英]Select dynamic DOM Elements in d3

I am trying to draw shapes and select and interact with them using D3. 我正在尝试绘制形状,并使用D3选择它们并与其进行交互。 I am learning D3, so need to understand some logic more clearly. 我正在学习D3,因此需要更清楚地理解一些逻辑。 I can draw shapes, I need to drag them while selecting a shape. 我可以绘制形状,选择形状时需要拖动它们。 I cannot seem to select the particular object when there are multiple objects drawn on canvas. 当在画布上绘制多个对象时,我似乎无法选择特定对象。

http://jsfiddle.net/nilarya/WKa8F/2/ this is where I have been so far, I request you to take a look at it,(the code is somewhat messy, I'm sorry, its late in here... :() if you draw multiple objects (Circles and/or Rectangles) on the canvas and then try to select one, you will notice the error. http://jsfiddle.net/nilarya/WKa8F/2/这是我到目前为止所到之处,请您看一下(代码有些混乱,很抱歉,它在这里很晚。 .. :()如果在画布上绘制多个对象(圆形和/或矩形),然后尝试选择一个对象,则会注意到该错误。

I have tried using 我尝试使用

d3.select(this)

and also 并且

d3.select(this.firstChild)

but I need to select a particular circle or rectangle. 但是我需要选择一个特定的圆形或矩形。 how do I do this? 我该怎么做呢?

Update your dragmove listener to handle only the selected shape, ie the shape to which this listener is binded to. 更新您的dragmove侦听器以仅处理选定的形状,即此侦听器绑定到的形状。 All you'll have to do is assign the selection of this by D3 to a variable, and use that instead of the external references, like so: 您所需要做的就是将D3 this选项的选择分配给一个变量,并使用它代替外部引用,如下所示:

function dragmove(d) {
    var shape = d3.select(this);
    if (isrectMov == true) {
        shape.attr("x", d3.event.x)
            .attr("y", d3.event.y)
            .attr("cursor", "move");
    } else if (islineMov == true) {
        shape.attr("x1", d3.event.x)
            .attr("y1", d3.event.y)
            .attr("x2", d3.event.x)
            .attr("y2", d3.event.y)
            .attr("cursor", "move");
    } else if (iscircleMov == true) {
        shape.attr("cx", d3.event.x)
            .attr("cy", d3.event.y)
            .attr("cursor", "move");
    } else {}
}

However, this will work only for similar shapes, the code has some more issues that needs to be addressed. 但是,这仅适用于相似的形状,该代码还有一些其他问题需要解决。 I suggest you start from scratch, and try not to use global variables at all, but instead require (or select ) any shape when you need it (eg inside a handler). 我建议您从头开始,尽量不要使用全局变量,而是在需要时(例如在处理程序内)要求(或选择 )任何形状。 This will reduce complexity as you no longer have to try to follow the state of each variable in your minds eyes. 这将降低复杂性,因为您不再需要尝试遵循每个变量的状态。


的jsfiddle图标 Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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