在 D3 中设置 <select> 元素的值?

Set the value of a <select> element in D3?

如何使用 D3.js 设置 <select> 元素的值?

我正在尝试这个:

d3.select('#myselect').attr('value', 'France');

但它不起作用。

JSFiddle 在这里:http://jsfiddle.net/06z9tnzs/

我可能错了,但是是因为你没有包括d3.js吗?

<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>

出于某种原因,我在框架源中看不到它。 还, select 的 ID 应该是我的select

<select>
    <option value="England">England</option>
    <option id = "myselect" value="France">France</option>
    <option value="Italy">Italy</option>
</select>

您需要使用 属性 而不是 attr 来设置值。

d3.select('#myselect').property('value', 'France');

来自 d3 文档:

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.

https://github.com/mbostock/d3/wiki/Selections#property

Albert 关于您的 JSFiddle 缺少 d3.js 引用并且未在 select 元素上指定 "myselect" 的 id 的评论也是正确的.

另一种设置值的方法d3.js

d3.select('#myselect').node().value = 'France';