我有一个键值列表,其中键是一个人类可读的名称,值应该适合链接,例如:
[
{"name": "The home page", "value": "/index.php"},
{"name": "The Pictures Section", "value": "/pics/index.html"},
...
]
链接的键值列表,例如:
[
{"name" : "My Site", "value:":"homesite.com/my_site"},
{"name" : "His Site", "value:":"homesite.com/his_site"},
{"name" : "Her Site", "value:":"homesite.com/her_site"},
...
]
我想有一个带有下拉菜单的网页和一个链接列表。用户将选择一个名称,并相应地附加链接列表。例如,如果用户选择了The Pictures Section
,则会显示以下列表:
<a href="homesite.com/my_site/pics/index.html"> My Site </a> <br>
<a href="homesite.com/his_site/pics/index.html"> His Site </a> <br>
<a href="homesite.com/her_site/pics/index.html"> Her Site </a> <br>
我该如何解决这个问题?
答案 0 :(得分:1)
var arraya = [
{"name": "The home page", "value": "/index.php"},
{"name": "The Pictures Section", "value": "/pics/index.html"},
...
]
var arrayb = [
{"name" : "My Site", "value:":"homesite.com/my_site"},
{"name" : "His Site", "value:":"homesite.com/his_site"},
{"name" : "Her Site", "value:":"homesite.com/her_site"},
...
]
//bind a click event to your a tags
$('a').click(function() {
//get the url of the tag
var url = $(this).attr('href');
loop through arrayb until you match the one you want
var site;
for (site in arrayb)
{
if (site.value == url)
{
break;
}
}
});
//loop through arraya matching on the name of the value matched above
var value;
for(value in arraya)
{
if (site.name == value.name)
{
break;
}
}
//this is your value
site.value;
});
答案 1 :(得分:1)
以下代码未经过测试,我只是编写它为您提供了一个起点。我希望这就是你要找的东西:
var sections = [
{"name": "The home page", "value": "/index.php"},
{"name": "The Pictures Section", "value": "/pics/index.html"},
...
],
urls = [
{"name" : "My Site", "value:":"homesite.com/my_site"},
{"name" : "His Site", "value:":"homesite.com/his_site"},
{"name" : "Her Site", "value:":"homesite.com/her_site"},
...
];
function generateSelectHtml() {
var html = '<select id="sections" onchange="showSescion(this);">';
for (var i = 0; i < sections.length; i++) {
html += '<option value="' + sections[i].value + '">' + sections[i].name + '</option>';
}
html += "</select>";
return html;
}
function generateSelectDom() {
var el = document.createElement("SELECT");
el.id = "sections";
el.onchange = function() { showSection(el); };
for (var i = 0; i < sections.length; i++) {
var option = document.createElement("option");
option.value = sections[i].value;
option.innerText = sections[i].name;
el.appendChild(option)
}
return el;
}
function showSection(box) {
var container = document.getElementById("listContainer");
for (var i = 0; i < urls.length; i++) {
var item = document.getElementById("a");
item.href = urls[i].value + box.value;
item.innerText = urls[i].name;
container.appendChild(item);
}
}
你当然会有很多改变。我做的是: generateSelectHtml 方法返回选择框的html,你可以将它添加到dom中:
document.getElementById("AN_ID").innerHTML = generateSelectHtml();
generateSelectDom 方法创建实际的dom元素,因此您只需使用 appendChild 将其添加到现有的dom中。
showSection 方法只将选定的值输出到id listContainer 的元素中。