如何在javascript文件中使用函数

时间:2017-11-05 17:09:52

标签: javascript requirejs

我如何在其他javascript中包含javascript文件?

它的前端javascript。

我不想包含在html中,我想在nodeJS中添加:

var jquery = require("jquery.js");
jquery.$("#c").style.color = "green";

我试过了:

const jqLink = 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js';
/* I try this, what give me a error, with requireJS */
define([jqLink], function(jq){
 return jq;
});

jq$("#c").style.color = "red";
<html><head><script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.5/require.js"></script>
</head>
<body><h1 id="h1tag">Im h1tag</h1>
</body>

PD:我也试过了:

Main.js:

 window.addEventListener("DOMContentLoaded",main);

function main(){
    scripts();
    var e = new ES();
    e.get("#ti").style.opacity = +true;
}

function scripts(){
    var list = ["es.js"], script = document.createElement("script"),b = document.head, i=0,max = list.length;
    for(;i<max;i++){
    script.src = list[i];
    b.appendChild(script);  
    }
}

ES.JS:

class ES{
    constructor(){  
    }
    get(symbol, e){
    let d = document;
    return symbol === "#" ? d.getElementById(e) : symbol === "." ? d.getElementsByClassName(e) : d.getElementsByTagName(e);
    }
}

1 个答案:

答案 0 :(得分:1)

这只是一个可能有用的调整。它将“包含”脚本加载到同一页面

function includeFile(path) {
    var imported = document.createElement('script');
    imported.src = path;
    document.head.appendChild(imported);
}

称之为:

includeFile('/path/to/other_js_file.js');