繁体   English   中英

运行外部javascript文件,可在html文件中编辑图形

[英]Running external javascript file that edits graph in html file

我的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,因此您还需要在标头中包含它。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

您还可以将jQuery和Plotly库放在您的Web服务器上,然后从那里加载它们,而不是此处的外部托管示例。 然后,您将使用网络服务器上库的相对路径,例如

<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}});
  });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM