我正在尝试使用 d3 附加一个输入 html 元素并在更改时读取文本值:
$scope.addField = function (parent) {
parent.append("br");
parent.append("input")
.attr("type", "input")
.attr("placeholder", "Add a comment ...")
.property("value", function (value) {
console.log("value: " + value); // logs: "value: undefined"
})
.text(function (value) {
console.log("text: " + value); // logs: "text: undefined"
})
.on("input", function (value) {
console.log("oninput: "+ value) // logs: "oninput: undefined"
})
.attr("id", ID_PREFIX + $scope.selection.id)
.attr("value", "hallo")
.on("change", function(d, i) {
console.log("change: " + d + " " + i); // logs: change: undefined 0
$scope.$apply(function () {
const elem = d3.select("#" + ID_PREFIX + $scope.selection.id)
.select("input");
console.log(elem);
// returns the html element but without the proper text information
$scope.setAnnotationComment({item: $scope.selection}, $scope.comment);
});
});
parent.append("br");
};
所以我无法获取输入字段的更改值。即使为输入字段分配一个唯一 id 并通过唯一 id 获取带有 d3 的 html 元素也不会返回字段“文本”、“值”或类似的东西。当我用 chrome 控制台检查 html 时,输入标签如下:
<input type="input" placeholder="Add a comment ...">
所以没有赋值属性。
还有其他可能吗?我想避免选择所有输入字段,例如:
d3.selectAll('input')
更新: 这是 JSFiddle 的更新版本:jsfiddle.net/jeannedark/8e96hef6/7 d3 的这个用例可能吗?如果不是,最好的方法/框架是什么,而不是附加一个平面 html 元素。我真的很欣赏添加属性等的 d3 风格。
最佳答案
这个确切的问题让我发疯,直到我滚动浏览 D3js docs寻找别的东西,然后发现了这个:
Some HTML elements have special properties that are not addressable using attributes or styles, such as a form field’s text value and a checkbox’s checked boolean.
使用selection.property(name[, value])
获取您需要的数据。
https://stackoverflow.com/questions/38993294/