gpt4 book ai didi

javascript - 如何从按钮运行 <script>

转载 作者:行者123 更新时间:2023-11-28 17:42:30 26 4
gpt4 key购买 nike

我是新的网页设计,我正在使用 javascript 库绘制一棵树。我的问题是它是在页面加载时自动绘制的。我想要一个按钮并单击这幅画,但我找不到如何操作。尝试将函数传递给 JavaScript 文件,但传递它时我不知道在 html 文件中如何调用它。

这是 fiddle https://jsfiddle.net/nse4w959/

<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var treeData = [
{
"name": "Top Level",
"parent": "null",
"children": [
{
"name": "Level 2: A",
"parent": "Top Level",
"children": [
{
"name": "Son of A",
"parent": "Level 2: A"
},
{
"name": "Daughter of A",
"parent": "Level 2: A"
}
]
},
{
"name": "Level 2: B",
"parent": "Top Level"
}
]
}
];
// ************** Generate the tree diagram *****************
var margin = {top: 40, right: 120, bottom: 20, left: 120},
width = 960 - margin.right - margin.left,
height = 500 - margin.top - margin.bottom;
var i = 0;
var tree = d3.layout.tree().size([height, width]);
var diagonal = d3.svg.diagonal().projection(function(d) { return [d.x, d.y]; });
var svg = d3.select("body").append("svg")
.attr("width", width + margin.right + margin.left)
.attr("height", height + margin.top + margin.bottom).append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
root = treeData[0];
update(root);
function update(source) {
// Compute the new tree layout.
var nodes = tree.nodes(root).reverse(),
links = tree.links(nodes);
// Normalize for fixed-depth.nodes.forEach(function(d) { d.y = d.depth * 100; });
// Declare the nodes…
var node = svg.selectAll("g.node").data(nodes, function(d) { return d.id || (d.id = ++i); });
// Enter the nodes.
var nodeEnter = node.enter().append("g").attr("class", "node")
.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")"; });
nodeEnter.append("circle").attr("r", 10).style("fill", "#fff");
nodeEnter.append("text").attr("y", function(d) {
return d.children || d._children ? -18 : 18; })
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.text(function(d) { return d.name; })
.style("fill-opacity", 1);
// Declare the links…
var link = svg.selectAll("path.link")
.data(links, function(d) { return d.target.id; });
// Enter the links.
link.enter().insert("path", "g")
.attr("class", "link")
.attr("d", diagonal);
}
</script>

最佳答案

调用按钮最简单的方法是

<button onclick="update()">Update</button>

关于javascript - 如何从按钮运行 &lt;script&gt;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47614598/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com