删除D3元素虽然我只添加了新元素

时间:2014-09-07 15:58:52

标签: javascript d3.js

自从我选择了以来已经有一段时间了,看起来我有点生疏了。我正在尝试创建一个表单,我可以点击+添加更多输入字段,然后点击-删除现有字段。

为了尝试发现我的错误,我开始分别用绿色,黄色和红色对enter(),更新和exit()进行着色。

原始数据数组有两个元素,因此它们显示为绿色:

enter image description here

然后我点击将一个新元素推送到数组的加号,我希望看到两个黄色和一个绿色,但我看到除了最后一个之外所有元素都被删除了,如果我点击+这会重复再次:

enter image description here

再加上:

enter image description here

我将我的代码与经典General Update Pattern进行了比较,除了我设置密钥的方式之外,我看不到任何重要的内容,我在其中使用了电子邮件。这是我添加的代码,用于修复另一个未添加所有框的基础问题,每个框中只有一个。

我的评论代码如下:

var renderFriends = function () {

  console.log("Rendering friends:" + friendsList)

  var friends = d3.select('.friends-container')
    .selectAll('div')
    .data(friendsList, function(d,i) {
      // this was something I added when I thought the problem were the keys
      return d
    })

  // updates will be yellow
  friends.classed("update", true)

  var enter = friends.enter()

  // Friend box
  // all the divs are because I'm using foundation css
  // the new class is what marks the font green
  var friendBox = enter.append('div').classed('large-12 columns new', true)

  friendBox.append('div').classed('large-8 columns', true)
    .append("input")
    .attr("type", "text")
    .attr("value", String)

  // Icon box
  var iconBox = friendBox.append('div').classed('large-2 left columns', true)
    .append("i")
    .classed('fi-minus', true)
    .on("click", function(d) {
      // out of scope for this question
      console.log("Removing:" + d)
      friendsList.remove(friendsList.indexOf(d))
      renderFriends()
     })

  // exit state should colour the fonts red
  friends.exit().classed('remove', true)

}

1 个答案:

答案 0 :(得分:1)

我用自定义样式做了一个小测试,这就是得到的(当我点击减号按钮时):

enter image description here

所有元素都有绿色背景,因为它们都有" new" class," update"元素有黄色边框,"删除"红色背景。 所以我注意到你有一个嵌套的各种Div,问题是当你做一个selectAll(' div')将选择所有的div并且d3期望每个div选择元素作为与其对应的数据元素。

所以如果你想添加另一个元素,你的friendsList是:

friendsList = ['a@test.com','b@test.com','c@test.com'];

d3.selectAll(' div')将占用6个div(当你有2个朋友并添加一个)时,它只会绑定3个元素,因为你的数据集只包含3个朋友,并且它将其余的元素定位为"退出"。

要解决此问题,只需使用像' .friend'这样的课程更改您的选择。并将其添加到每个要插入的元素(仅主容器div); 像这样:

http://jsfiddle.net/2codv59e/

相关问题