【问题标题】:javascript use url as string for arrayjavascript使用url作为数组的字符串
【发布时间】:2017-02-07 19:48:05
【问题描述】:

我有一个带有数组的外部 .js。

test = [
{
    "name": "1"
}
test2 = [
{
    "name": "2"
}
];

现在我想使用 url 来识别数组的名称。 因此,如果有人继续使用 test.html,他正在使用 test 数组和 test2.html test2 数组。

如果我使用

var queryArray = window.location.search.substring(1);

var queryArray = window.location.href

或者类似的,然后

document.getElementById("demo").innerHTML = queryArray.name;

它不起作用,因为他当然在寻找不存在的数组queryArray。 有没有办法使用 url 作为标识符?

希望你能理解重点^^

感谢每一个想法!!!

【问题讨论】:

标签: javascript jquery arrays json var


【解决方案1】:

如果您能够稍微调整指定“数组”的方式,您可能会执行以下操作:

// =============================
// 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);

【讨论】:

  • 这太棒了!!!正是我想要的。现在我试着理解数组的具体拼写。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2011-05-02
  • 2017-05-29
  • 2020-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-05
  • 1970-01-01
相关资源
最近更新 更多