如何在没有事件的情况下调用js函数

Col*_*een 9 html javascript jquery events function

如何在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>
Run Code Online (Sandbox Code Playgroud)

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

例如,我得到了show_graph(bar,[[1,2000],[2,50],[3,400],[4,200],[5,5000]],['Foo']);

我该怎么办?

编辑:

我很欣赏这些反馈,但我尝试将其包装在脚本标签中并获得"参数数量无效"错误.

javascript是:

function show_graph(charttype, data, options){

    var chart_options = {
        series: {
            charttype: {
                show: true
            }
        }
    }

    var plot = $.plot($("#chart1"), [data], [chart_options]);
}
Run Code Online (Sandbox Code Playgroud)

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

use*_*716 14

将其包裹在<script>标签中:

<body>

<div id="chart1" style="width:600px;height:300px"></div>

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

</body>
Run Code Online (Sandbox Code Playgroud)

...虽然我不知道模板是如何影响的.我想它会呈现相同的.

  • @KNU 有点晚了,但是使用 {{}},您可以拥有 char_type、data 和 options 变量的值。 (2认同)

Joe*_*man 5

您需要将函数调用包装在脚本标记中,如下所示:

<script type="text/javascript">
show_graph({{ chart_type }}, {{ data }}, {{ options }});
</script>
Run Code Online (Sandbox Code Playgroud)

如果您需要验证为 XHTML,您还应该使用 CDATA 进行包装。请参阅脚本标记中何时需要 CDATA 部分?对此的参考。


Dem*_*tic 5

还有一个答案:

<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>
Run Code Online (Sandbox Code Playgroud)