javascript - 如何使用 D3.js 将两个按钮添加到一个 div?

标签 javascript html css d3.js

我正在尝试向一个 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>

最佳答案

问题是您尝试将内容附加到表单后设置表单的html。所以换句话说,附加函数起作用,然后你销毁所有东西并将它换成你的 .html 函数中的内容。

要么将此 block 移动到附加调用之前:

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/

关于javascript - 如何使用 D3.js 将两个按钮添加到一个 div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33351320/

相关文章:

javascript - prevAll() 在更复杂的 DOM 中不起作用

javascript - 我的 javascript showhide 代码上的奇怪错误

javascript - 使用嵌套数组对象迭代数组的属性

html - 需要更改响应主题中的 div 位置

javascript - 带参数的递归方法

javascript - 使 flex 元素一次包裹两个

html - 伪元素和填充

javascript - 由于窗口宽度,需要根据缩放比例将元素与其兄弟元素垂直对齐

javascript - Accordion 内容的动画

javascript - AngularJS,变量的嵌套 Controller