【问题标题】:How to add two buttons to a div with D3.js?如何使用 D3.js 向 div 添加两个按钮?
【发布时间】:2015-10-26 16:56:27
【问题描述】:

我正在尝试将两个按钮添加到一个 div,一个在另一个下方。第一个按钮接受一个数字,第二个按钮用于打开和关闭线路。

只创建了我附加的第二个按钮。如何在同一个 div 中创建两个按钮?

这是JSFiddle.

<!DOCTYPE html>
<meta charset="utf-8">
<html>
<script src="d3.js"></script>
<body>
<div id=options>
<script>

(function(){
  var form = d3.select("#options")
      .append("form")
      .html("Enter a number:")

  form.append("input")
      .attr("type", "text")
      .attr("name", "num")

  form.append("input")
      .attr("type", "button")
      .attr("value", "Add")
      .attr("onclick", "printNum(num.value)")

  form.html("Show/hide lines:")    
      .append("input")
      .attr("type", "button")
      .attr("name", "toggle")
      .attr("value", "Toggle")
      .attr("onclick", "togglePressed()");
})();

function printNum(num){
  alert("You entered " + num + "!");
}

function togglePressed(){
  alert("You pressed the toggle button!");
}
</script>
</div>
</body>
</html>

【问题讨论】:

    标签: javascript html css d3.js


    【解决方案1】:

    问题是您在 试图将内容附加到表单之后设置了表单的 html。换句话说,附加函数起作用,然后你销毁所有内容并将其替换为 .html 函数中的内容。

    要么将此块移动到 追加调用之前:

    form.html("Show/hide lines:")    
      .append("input")
      .attr("type", "button")
      .attr("name", "toggle")
      .attr("value", "Toggle")
      .attr("onclick", "togglePressed()"); 
    

    或者,不要使用.html 函数。

    参考:“设置内部 HTML 内容将替换任何现有的子元素”https://github.com/mbostock/d3/wiki/Selections#html

    更新的 jsfiddle:http://jsfiddle.net/kueuLLr4/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多