简体   繁体   English

如何用d3更新文本输入的内容?

[英]How to update the contents of a text input with d3?

I am trying to create a text input control in D3 that needs to push data into the text input. 我试图在D3中创建一个文本输入控件,需要将数据推送到文本输入。 I am able to set the initial value with 我能够设置初始值

d3.selectAll('#textfield')
    .data([number])
    .attr('value', function(d) { return d })

but this is of no use once someone edits the text and then tries the external update. 但是,一旦有人编辑文本然后尝试外部更新,这是没用的。 Is there some way of setting the contents to some arbitrary value? 有没有办法将内容设置为某个任意值?

I've got the code in JsFiddle . 在JsFiddle中得到了代码

Update: 更新:

I've found a workaround : 我找到了一个解决方法

var node = d3.selectAll('#textfield')
    .data([number])
    .node()
node.value = number

But I'm not sure if this is the right approach. 但我不确定这是否是正确的方法。 Any clues? 有线索吗?

You are setting the value of the value attribute and value just happens to be a special attribute which does not play well with setAttribute function (which d3 internally uses for setting an attribute). 您正在设置 value属性的value ,而恰好是一个特殊属性,它与setAttribute函数( d3内部用于设置属性)无关。

This approach is not much better, but more pragmatic use of D3 : 这种方法并没有好多少,但更实际的使用D3

d3.selectAll('#textfield')
    .data([number])
    .each(function (d) {
        this.value = d;
    });

Demo: http://jsfiddle.net/LGtDD/3/ 演示: http//jsfiddle.net/LGtDD/3/


Besides, one can (and perhaps should ) use plain JS to do this unless you have a compelling argument against it. 此外,人们可以(也许应该 )使用普通的JS来做到这一点,除非你有一个令人信服的论据。 Using D3 for this might just be overkill: 使用D3可能只是过度杀伤:

document.getElementById('textfield').value = number;

您可以使用设置文本输入值

d3.select('#textfield').property('value', "<your desired text>");

This also seems to works: 这似乎也有效:

function changeValue() {
    var number = Math.round(Math.random()*100);
    d3.select('#textfield')[0][0].value = number;
}

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

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