我的 html 页面中有一个按钮,我想在单击该按钮后运行外部 javascript 文件。
<input type="button" id="btn" value="Show Graph" onclick=src="graph.js">
有问题的 JavaScript 文件是:
$(document).ready(function(){
$("#btn").click(function(){
$("#tester").load("", function(){
TESTER = document.getElementById("tester");
Plotly.plot(TESTER,[{
x: [1,2,3,4,5,6,7,8,9,10],
y: [1,4,9,16,25,36,49,64,81,100]}],
{margin: {t:0}});
});
});
});
此文件的目标是在以下位置编辑和绘制图表:
<div id ="tester" style="width:600px;height250px;">
</div>
我需要做什么才能让我的 javascript 文件能够编辑 html 页面上的元素?
最佳答案
您似乎想使用plotly.js。首先,您必须将库包含在 HTML 文档的头部
<head>
...
<script type="text/javascript" src="https://cdn.plot.ly/plotly-latest.min.js"></script>
...
</head>
然后你可以添加你发布的功能,但你应该稍微修改一下
<head>
...
<script type="text/javascript" src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#btn").click(function(){
Plotly.plot(document.getElementById("tester"),
[{ x: [1,2,3,4,5,6,7,8,9,10],
y: [1,4,9,16,25,36,49,64,81,100]}],
{margin: {t:0}});
});
});
</script>
...
</head>
这会将绘图函数调用添加到 ID 为 btn 的按钮的 onClick 事件中。按钮的 HTML 声明不再需要设置 onclick 事件,因此它应该如下所示
<input type="button" id="btn" value="Show Graph">
请注意,您的 javascript 使用 jQuery,因此您还需要将其包含在 header 中。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
您还可以将 jQuery 和 Plotly 库放在您的网络服务器上并从那里加载它们,而不是此处的外部托管示例。然后您将使用网络服务器上库的相对路径,例如
<script src="js/jquery.min.js"></script>
如果您希望该函数位于单独的 javascript 文件中,请将对该函数的调用放入按钮中
<input type="button" value="plot" onclick="drawPlot()">
然后将函数写入文本文件,即 myplot.js,然后将其包含在标题中
<script type="text/javascript" src="myplot.js"></script>
你必须像这样修改你的函数
function drawPlot () {
Plotly.plot(document.getElementById("tester"),
[{ x: [1,2,3,4,5,6,7,8,9,10],
y: [1,4,9,16,25,36,49,64,81,100]}],
{margin: {t:0}});
});
}
关于javascript - 运行外部 javascript 文件来编辑 html 文件中的图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48628986/