我有一个带阵列的外部.js。
test = [
{
"name": "1"
}
test2 = [
{
"name": "2"
}
];
现在我想使用url来识别数组的名称。 因此,如果有人使用test.html,他正在使用测试数组和test2.html test2数组。
如果我使用
var queryArray = window.location.search.substring(1);
或
var queryArray = window.location.href
或类似的东西然后
document.getElementById("demo").innerHTML = queryArray.name;
它不起作用,因为他当然正在寻找一个不存在的数组queryArray
。
有没有办法将url用作标识符?
我希望你能理解这一点^^
每个想法的THX !!!
答案 0 :(得分:0)
如果您能够稍微重新调整指定"数组"的方式。你可能会这样做:
// =============================
// Similar but a little more tidy
// This also supports file names with characters like "-" or complete url strings
// =============================
var dataItems = [
{key : "test1", value: [{"name": "This is test 1"}]},
{key : "test2", value: [{"name": "This is test 2"}]},
{key : "js", value: [{"name": "This is the sandbox"}]} // This sandbox (I think)
];
// =============================
// =============================
// You migth now use the full pathname as the data item key,
// but if you wanted to use the "name" of the file you might do something like this.
// =============================
var currentFileName = location.pathname.split("/").pop().split(".html")[0];
// =============================
// =============================
// You might want to do this in several steps to handle stuff like filter returning
// no hits.
// =============================
var dataItem = dataItems.filter(function(item){ return item.key === currentFileName;})[0];
// =============================
console.log(dataItem.value[0].name);