几天来,我一直在寻找这个答案,虽然有很多关于如何在项目中包含文件的主题(也在 Stack Overflow 上),但我还没有找到解决我的问题的方法。
我正在做一个项目,我想一次包含一个对象,来自许多不同的文件(我不想包含文件本身,只包含它们的内容)。所有文件中的所有对象都同名,只是内容不同。
重要的是我不会在页面的 head 部分获得 SCRIPT 标记,因为文件中的所有内容都将具有相同的名称。无论如何,这些文件都没有函数,只有一个对象,需要一次加载一个对象,然后在加载下一个元素时丢弃。
这些对象将保存将在页面上显示的数据,并且将通过“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.
}
现在,当我单击菜单项时,会触发 pageName 函数,并且我也将 HTML 元素发送到该函数,正是在这里,我希望将外部文件中的内容加载到本地变量中并用于在页面上显示内容。
我想要的答案是“如何将外部 obj 加载到我需要的函数中?” (它可能是一个外部文件,但仅限于不包含在项目的头部分中)。我仍在从我自己的本地库中加载文件。
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 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 = ' --||-- ';
}
任何帮助将不胜感激,
莫勒