最初我有这样的布局:
<ul id="state_${abbr}"></ul>
在jsp页面上,我需要将map的JSON映射加载到布局中。
coverage.phone.data = {
"CA" : {
"LOS ANGELES" : "1111",
"TORRANCE" : "2222",
"SANTA MONICA" : "3333"
},
"UT" : {
"APPLE VALLEY" : "4444",
"SALT LAKE CITY" : "5555"
},
"NV" : {
"BOULDER CITY" : "6666",
"LAS VEGAS" : "7777",
"CARSON CITY" : "8888"
}
}
最终的结果是这样的:
<ul id="state_CA">
<li><p>City: <a id="1111" href="#">LOS ANGELES</a></p></li>
<li><p>City: <a id="2222" href="#">TORRANCE</a></p></li>
<li><p>City: <a id="3333" href="#">SANTA MONICA</a></p></li>
</ul>
<ul id="state_UT">
<li><p>City: <a id="4444" href="#">APPLE VALLEY</a></p></li>
<li><p>City: <a id="5555" href="#">SALT LAKE CITY</a></p></li>
</ul>
<ul id="state_NV">
<li><p>City: <a id="6666" href="#">BOULDER CITY</a></p></li>
<li><p>City: <a id="7777" href="#">LAS VEGAS</a></p></li>
<li><p>City: <a id="8888" href="#">CARSON CITY</a></p></li>
</ul>
它将列出每个州区域的城市名称和位置 ID。 “li”标签中的每个链接都有一个 onclick 事件。 click 函数将触发一些后端调用,发送位置 id,这将是请求中 a 标签的 id。
查找迭代映射,我找到了 jQuery.each()因此,我编写了以下 JavaScript 来填充无序列表“ul”。
// create the li and click function
var createLink = function(map) {
var link = "";
$.each(map, function(key, value){
link += "<li><p>City: <a id=\"" + value + "\" href=\"#\">" + key + "</a></p></li>";
$("#"+value).click(function(){
callBackend(this);
});
});
return link;
};
// append the li(s) to the ul tags
$.each(coverage.phone.data, function(i, val){
var result = createLink(val);
$("#state_"+i).append(result);
});
本质上,我需要迭代 JSON 映射对象来填充列表。我不太喜欢将每个函数与任何单击事件嵌套。
不幸的是,没有附加任何内容,我不明白为什么。任何帮助将不胜感激。
最佳答案
看看这个
$(function(){
/ create the li and click function
var createLink = function(map) {
var link = "";
$.each(map, function(key, value){
link += "<li><p>City: <a id=\"" + value + "\" href=\"#\">" + key + "</a></p></li>";
$("#"+value).click(function(){
callBackend(this);
});
});
return link;
};
// append the li(s) to the ul tags
$.each(coverage.phone.data, function(i, val){
var result = createLink(val);
$("#state_"+i).append(result);
});
});
关于jquery - Javascript 迭代 map 的 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6879160/