使用D3在选定的单选按钮之间切换

时间:2016-12-10 11:44:10

标签: javascript d3.js

考虑我有4个单选按钮,如html

<form id="form">
    <input type="radio" name="stack" value="north">north<br>
    <input type="radio" name="stack" value="east" >east<br>
    <input type="radio" name="stack" value="west">west<br>
    <input type="radio" name="stack" value="south">south
</form>

如何使用D3.js获取所选单选按钮的值并在选择时分配到全局变量,这样我可以在选择之间切换?

1 个答案:

答案 0 :(得分:6)

如果这些是输入,您可以执行以下操作:

d3.selectAll("input").on("change", function(){
    console.log(this.value)
});

要仅选择该特定的单选按钮组,请使用他们的name

d3.selectAll("input[name='stack']").on("change", function(){
    console.log(this.value)
});

将其分配给全局(无var声明):

d3.selectAll("input[name='stack']").on("change", function(){
    globalVariable = this.value;
});

以下是演示:

d3.selectAll(("input[name='stack']")).on("change", function(){
console.log(this.value)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<form id="form">
    <input type="radio" name="stack" value="north">north<br>
    <input type="radio" name="stack" value="east" >east<br>
    <input type="radio" name="stack" value="west">west<br>
    <input type="radio" name="stack" value="south">south
</form>