gpt4 book ai didi

javascript - 简单的 D3.js 文本选择

转载 作者:行者123 更新时间:2023-11-29 17:59:01 26 4
gpt4 key购买 nike

我遇到了一个使用 D3 来创建简单的类似表单的体验的奇怪场景。

流程是这样的……

1)使用D3创建元素,带默认值

2) 将函数绑定(bind)到按钮以读取此文本区域的值并执行操作

var content = d3.select('#content');
content.append('div')
.append("input")
.attr("type", "text")
.attr("id", "textinput")
.attr("size", "40")
.attr("value","Default Text");

content.append('div')
.html('Get contents...')
.on("click", function () {
console.log("D3 Selection: " + d3.select("#textinput").attr('value'));
console.log("DOM Selection: " + document.getElementById("textinput").value);
});

DOM 选择的值是用户输入的任何值,无论用户输入什么,D3 选择的值始终是“默认文本”:

D3 Selection: Default Text
DOM Selection: I typed something

我缺少什么(除了明显的知识、技能等 - 在我看来,我这样做主要是为了好玩)? D3 选择器不应该以这种方式运行吗?

戴夫

最佳答案

您应该使用 .property() 而不是使用 .attr()。

根据:https://github.com/d3/d3-3.x-api-reference/blob/master/Selections.md#property

Some HTML elements have special properties that are not addressable using standard attributes or styles. For example, form text fields have a value string property, and checkboxes have a checked boolean property. You can use the property operator to get or set these properties, or any other addressable field on the underlying element, such as className.

之所以可以通过 .attr() 方法设置值,但不能获取它,是因为 .attr() 与底层 HTML 交互。用户交互不会影响 HTML,因此当您通过 .attr() 获取这些更改时不会反射(reflect)出来。

编辑:更新了指向 d3v3 API 的链接。这同样适用于 d3v4,尽管描述略有不同:https://github.com/d3/d3-selection/blob/master/README.md#selection_property

关于javascript - 简单的 D3.js 文本选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36582403/

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