简体   繁体   English

包括来自外部.js文件的对象

[英]Including objects from external .js files

I have been searching for many hours over several days for this answer and though there are many topics on how to include files in a project (also here at Stack Overflow), I have not yet found THE solution to my problem. 我在几天里一直在寻找这个答案很多小时,尽管有很多关于如何在项目中包含文件的话题(也在此处的Stack Overflow中),但我还没有找到解决问题的方法。

I'm working on a project where I want to include one single object at a time, from many different files (I do not want to include the files themselves, only their content). 我正在一个项目中,我想一次包含多个不同文件中的一个对象(我不想包含文件本身,而只包含它们的内容)。 All the object in all the files have the same name, only the content is different. 所有文件中的所有对象都具有相同的名称,只是内容不同。

It is important that I do not get a SCRIPT tag in the head section of the page as all the content from the files will have the same names. 重要的是,我不要在页面的头部获得SCRIPT标记,因为文件中的所有内容都具有相同的名称。 None of the files will have functions anyways, only one single object, that will need to be loaded one at the time and then discarded when the next element is loaded. 这些文件都不会具有任何功能,只有一个对象当时需要一个,然后在加载下一个元素时被丢弃。

The objects will hold the data that will be shown on the page and they will be called from the menu by an 'onclick' event. 这些对象将保存将在页面上显示的数据,并通过“ onclick”事件从菜单中调用它们。

function setMenu()   //   The menu is being build.
{
    var html = '';
    html += '<table border="0">';
    for (var i = 0; i<menu.pages.length; i++)    
    {
        html += '<tr class="menuPunkt"><td width="5"></td><td onclick="pageName(this)">'+ menu.pages[i] +'</td><td width="5"></td></tr>';
    }
    //   menu is a global object containing elements such as an array with
    //   all the pages that needs to be shown and styling for the menu.

    html += '</table>';

    document.getElementById("menu").innerHTML = html;
    style.setMenu();   //   The menu is being positioned and styled.
}

Now, when I click on a menu item the pageName function is triggered and I'm sending the HTML element to the function as well, it is here that I want the content from my external file to be loaded into a local variable and used to display content on the page. 现在,当我单击菜单项时,将触发pageName函数,并且还将HTML元素发送给该函数,正是在这里,我希望将外部文件中的内容加载到本地变量中并用于在页面上显示内容。

The answer I want is "How to load the external obj into the function where I need it?" 我想要的答案是“如何将外部obj加载到需要的函数中?” (It may be an external file, but only in the term of not being included in the head section of the project). (它可能是一个外部文件,但仅在未包含在项目的开头部分中)。 I'm still loading the the file from my own local library. 我仍在从自己的本地库加载文件。

function pageName(elm)   // The element that I clicked is elm.
{
    var page = info.innerHTML;    // I need only the innerHTML from the element.
    var file = 'sites/' + page + '.js';   // The file to be loaded is created.
    var obj = ??      // Here I somehow want the object from the external file to be loaded.
// Before doing stuff the the obj.
    style.content();
}

The content from the external file could look like this: 外部文件中的内容可能如下所示:

// The src for the external page: 'sites/page.js'

var obj = new Object()
{
    obj.innerHTML = 'Text to be shown';
    obj.style = 'Not important for problem at hand';
    obj.otherStuff = ' --||-- ';
}

Any help will be appreciated, 任何帮助将不胜感激,

Molle 莫尔

Using the following function, you can download the external js file in an ajax way and execute the contents of the file. 使用以下功能,您可以以ajax方式下载外部js文件并执行文件的内容。 Please note, however, that the external file will be evaluated in the global scope, and the use of the eval is NOT recommended. 但是请注意,将在全局范围内评估外部文件,并且不建议使用eval。 The function was adopted from this question. 该功能是从问题采用的。

function strapJS(jsUrl) {

    var jsReq = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    if (jsReq === null) {
        console.log("Error: XMLHttpRequest could not be initiated.");
    }
    jsReq.onload = function () {
        try {
            eval(jsReq.responseText);
        } catch (e) {
            console.log("Error: The script file contains errors." + e);
        }
    };
    try {

        jsReq.open("GET", jsUrl, true);
        jsReq.send(null);

    } catch (e) {
        console.log("Error: Cannot retrieving data." + e);
    }
}

JSFiddle here JSFiddle 在这里

Edit: 1 编辑:1

After some refactoring, I came up with this: 经过一些重构,我想到了这个:

function StrapJs(scriptStr, jsObjName) {
    var self = this;
    self.ScriptStr = scriptStr;
    self.ReturnedVal = null;

    function _init() {
        eval(self.ScriptStr);
        self.ReturnedVal = eval(jsObjName);
    }

    _init();
}

You can then get the script string any way you want and just instantiate a new StrapJs object with the script string and name of the object to return inside the script string. 然后,您可以按任何需要的方式获取脚本字符串,只需实例化带有脚本字符串和对象名称的新StrapJs对象以在脚本字符串中返回即可。 The ReturnedVal property of the StrapJs object will then contain the object you are after. 然后,StrapJs对象的ReturnedVal属性将包含您所追求的对象。

Example usage: 用法示例:

var extJS = "var obj = " +
    "{ " +
    "    innerHTML : 'Text to be shown', " +
    "    style : 'Not important for problem at hand', " +
    "    otherStuff : ' --||-- ' " +
    "}; ";

var extJS2 = "var obj = " +
    "{ " +
    "    innerHTML : 'Text to be shown 2', " +
    "    style : 'Not important for problem at hand 2', " +
    "    otherStuff : ' --||-- 2' " +
    "}; ";

var strapJS = new StrapJs(extJS, 'obj');
var strapJS2 = new StrapJs(extJS2, 'obj');
console.log(strapJS.ReturnedVal.innerHTML);
console.log(strapJS2.ReturnedVal.innerHTML);

See it in action on this fiddle 这个小提琴上看到它的实际效果

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

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