簡體   English   中英

如何將javascript函數從html文件移動到js文件並從html調用它?

[英]How to move a javascript function from an html file to a js file and call it from the html?

Javascript新手在這里。 我有一個嵌套在html文件中的javascript函數,我導入了一個外部庫abaaso ,然后聲明該函數,然后調用它:

<!DOCTYPE html>
<html>
<head>
    <title>title</title>
    <script src="abaaso.js"></script>
</head>

<body>

<script>
    var baseurl = "https://example.com";
    var baseapi = baseurl + "/api/v1/";
    var api_username = "user";
    var api_key = "key";
    var credentials = "?api_username=" + api_username + "&api_key=" + api_key;
    var rawdata = {};

    (function ($$) {

        /* login */
    login = function(username, password) {
    var calledUrl = baseapi + "user/login/" + credentials;
    calledUrl.post(
        function (content) {
            /*console.log("success" + JSON.stringify(content, null, 4));*/
        },
        function (e) {
            console.log("it failed! -> " + e);
        },
        {
                "username": username,
                "password": password

        },
        {"Accept" : "application/json"}
    );
    }

})(abaaso);

login('test@example.com', 'passwd');

</script>
</body>
</html>

我想將其放在外部.js文件中並導入,並且僅使用對函數login('test@example.com', 'passwd');的調用login('test@example.com', 'passwd'); 我不想從html文件中導入abaaso ,而是從新的.js中導入。

我怎樣才能做到這一點? 有沒有值得尊重的特殊結構? 我需要為js文件創建全局函數嗎?

我不想從html文件中導入abaaso,而是從新的.js中導入。

你不能那樣做。 但是,您可以導入abaaso和新的.js:

<head>
  <title>title</title>
  <script src="abaaso.js"></script>
  <script src="new.js"></script>
</head>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM