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