繁体   English   中英

如何使用html链接调用外部js?

[英]How can i call an external js using html link?

您好,当我在该范围内创建一个函数时,在该函数之外将不可见。 有没有另一种方法可以调用resettimeline函数而不将其置于本地范围之外? 我还需要调用ganttChart(config)函数中的许多其他函数,并且无法仅通过调用将它们移出该函数。

index.html

<!DOCTYPE html>
<html>
<head>
  <title>Gantt Chart</title>
  <link rel="stylesheet" type="text/css" href="style.css"> 
</head>
<body>
  <div class="chart" id="Chart" style="width: 100%"></div>
  <script src="https://d3js.org/d3.v3.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
  <script type="text/javascript" src="ganttChart.js"></script>
  <script type="text/javascript" src="app.js"></script>
   <a id="myButton" href="javascript:void(0);" onclick="resettimeline()" >Click here</a>
  <br/>
  <a href="javascript:updateData()" >Update</a>

</body>
</html>

app.js

  var data = [
  {
    id: 1,
    title: "Request received", 
    action: 'from',
    user: 'SAS',
    start_date: "08/08/2016", 
    end_date: "10/08/2016",
    value: 67,
    // term: "Short Term",
    completion_percentage: 29,
    color: "#770051",
  }
];

ganttChart(config);

ganttChart.js

function ganttChart(config) {
.
.
.
. 
        function resettimeline() {
            document.location.reload();
        };
}

尽管您的问题尚不完全清楚,但这听起来像是“ 揭示模块模式”的工作 ,这是控制范围的一种常用方法。

原理是采用立即调用函数表达式 (IIFE),该函数表达式仅在外部作用域中公开您需要的函数部分。

下面的伪代码描述了原理...

/* a function calls itself */
var invokedFunction = (function() {

    /* scoped (private) variables */
    var someValue = 20;
    var someOtherValue = 0;

    /* scoped (private) method */
    function _someMethod1() {
        return someValue + someOtherValue;
    }

    /* scoped (public) method */
    function someMethod2(num) {
        /* some action or process */
        someOtherValue += num || 1;

        /* return private method1 */
        return _someMethod1();
    }

    /* expose public method2 */
    return {
        method: someMethod2
    };

}());

console.log( invokedFunction.method() ); // => 21
console.log( invokedFunction.method(4) ); // => 25

除了someMethod2函数(该函数通过invokedFunction的返回值公开)之外, invokedFunction()所有工作都invokedFunction()损害。

进一步的解释可以在这里找到:

希望有帮助:)

let gc = gantChart(config);
gc.resettimeline(); // weeeee a loop!
.
.
function gantChart(config)
{
.
.
.
    return {resettimeline: resettimeline, gotonext: gotonext };
}

只需将要公开的所有功能添加到{}中,就像我对resettimeline所做的那样

暂无
暂无

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

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