gpt4 book ai didi

javascript - D3 元素被删除,尽管我只是添加新元素

转载 作者:行者123 更新时间:2023-12-03 11:53:26 25 4
gpt4 key购买 nike

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

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

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

enter image description here

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

enter image description here

再次加上:

enter image description here

我将我的代码与经典的 General Update Pattern 进行了比较除了我使用电子邮件设置按键的方式之外,我看不到任何重要的东西。这是我添加的代码,用于解决另一个根本问题,即并非所有框都被添加,而是每 3 个框中添加一个。

我的注释代码如下:

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)

}

最佳答案

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

enter image description here

所有元素都有绿色背景,因为它们都有"new"类,“更新”元素有黄色边框,“删除”元素有红色背景。所以我注意到你有一个不同的 Div 嵌套,问题是当你执行 selectAll('div') 将选择所有 div 并且 d3 期望每个被选择的 div 元素是一个数据与其对应的元素。

因此,如果您想添加另一个元素,并且您的 FriendsList 是:

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

d3.selectAll('div') 将采用 6 个 div(当您有 2 个 friend 并添加一个时),并且它只会绑定(bind) 3 个元素,因为您的数据集仅包含 3 个 friend ,并且它的目标是其余元素为“退出”。

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

http://jsfiddle.net/2codv59e/

关于javascript - D3 元素被删除,尽管我只是添加新元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25712146/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com