javascript - 使用 D3 确定选择/选项

标签 javascript html d3.js

组装一些之后radio buttons使用 D3

function build_rb() {
    let mylist = d3.range(5);
    let spans = d3.select('body')
                  .selectAll('span')
                  .data(d3.range(5))
                  .enter()
                  .append('span');
    spans.append('input')
         .attr('type', 'radio')
         .attr('name', 'rbname')
         .attr('id', d => d);
    spans.append('label')
         .html(d => ("display: " + d))
         .attr('for', d => d);
}
function get_rb() {
    let sel = d3.select('input[name="rbname"]:checked')
                .node().id;
    return sel;
}
build_rb();
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

我可以determine通过调用 get_rb() 选中单选按钮。

如果我对选择/选项结构做同样的事情

function build_so() {
    d3.select('body')
      .append('select')
      .attr('id', 'soname')
      .selectAll('option')
      .data(d3.range(5))
      .enter()
      .append('option')
      .attr('value', d => d)
      .text(d => ("display: " + d));
}
function get_so() {
    let select = document.getElementById('soname');
    let current = select.options[select.selectedIndex].value;
    return current;
}
function get_so_d3() {
    let select = d3.select('select[name="soname"]:checked');
    let current = select.node().id;
    return current;
}
build_so();
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

我可以找到使用准系统 JS (get_so) 选择的选项,但不能使用 D3 (get_so_d3)。

为什么?

相关:1 , 2 , 3

最佳答案

因为你的选择器是错误的。 :checked 应该在 option 上,而不是 select。并且您通过 name 属性进行选择,但“soname”被定义为一个 id。

function build_so() {
    d3.select('body')
      .append('select')
      .attr('id', 'soname')
      .selectAll('option')
      .data(d3.range(5))
      .enter()
      .append('option')
      .attr('value', d => d)
      .text(d => ("display: " + d));
}
function get_so_d3() {
    let select = d3.select('select[id="soname"] option:checked');
    let current = select.datum();
    return current;
}
build_so();
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<button onclick="console.log(get_so_d3())">console log</button>

关于javascript - 使用 D3 确定选择/选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56602894/

相关文章:

javascript - d3.queue 从不触发 .await 函数

javascript - 如何在网站完全加载之前隐藏加载屏幕?

javascript - 双击 Jquery 中的歧义?

javascript - 传递多个值以使用anchorscroll

javascript - 使用 Javascript 呈现 HTML 的策略

html - 在 html 表格中对齐按钮。 IE问题(楼梯问题)

variables - 传递 Javascript Alert 一个值

javascript - 您可以将 javascript 注入(inject) ERB 文件吗?

javascript - D3 SVG 无法响应调整大小

javascript - 有没有办法用 D3.js 修改 Vega 图表?