如何调用js函数没有事件

how to call js function without event

本文关键字:函数 事件 js 何调用 调用      更新时间:2023-09-26

我怎么能从html文件内调用js函数,没有事件触发器?我想有这样的代码:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="jquery.flot.js"></script>
<script src="chart.js"></script>
<title>
</title>
</head>
<body>
<div id="chart1" style="width:600px;height:300px"></div>
show_graph({{ chart_type }}, {{ data }}, {{ options }});
</body>
</html>

,但这只是导致函数调用被打印到屏幕上,而不是实际执行函数。

。我得到show_graph(酒吧,[[2000],[2,50],[400],[200],[5000]],["Foo"]);

我该怎么办?

编辑:

我很感激你的反馈,但我试着把它包装在一个脚本标签中,却得到了一个"参数数量无效"的错误。

javascript是:

function show_graph(charttype, data, options){
    var chart_options = {
        series: {
            charttype: {
                show: true
            }
        }
    }
    var plot = $.plot($("#chart1"), [data], [chart_options]);
}

所以我想真正的问题是"当我传递3个参数并接受3个参数时,为什么我得到一个"参数无效数量"的错误?"

<script>标签换行:

<body>
<div id="chart1" style="width:600px;height:300px"></div>
<script type="text/javascript">
    show_graph({{ chart_type }}, {{ data }}, {{ options }});
</script>
</body>

…虽然我不知道模板是怎么起作用的。

又一个答案:

<script type="text/javascript">
    (function() {
        // The following code will be enclosed within an anonymous function
        var foo = "Goodbye World!";
        document.write("<p>Inside our anonymous function foo means '" + foo + '".</p>');
    })(); // We call our anonymous function immediately
</script>

您需要像这样将函数调用包装在脚本标签中:

<script type="text/javascript">
show_graph({{ chart_type }}, {{ data }}, {{ options }});
</script>

如果需要验证为XHTML,还应该使用CDATA包装。请参阅何时在脚本标记中需要CDATA部分?

放到<script>标签中

<script type='text/javascript'>show_graph({{ chart_type }}, {{ data }}, {{ options }});</script>

添加脚本标签

<script>
show_graph({{ chart_type }}, {{ data }}, {{ options }});
</script>

应该在加载页面时调用该函数。要使用jQuery这样做,请使用以下代码:

<script type="text/javascript">
  $(document).ready(function() {
    show_graph({{ chart_type }}, {{ data }}, {{ options }});
  });
</script>