我想知道如何使用json对象数组作为输入动态生成HTML列表。
{title: "Title1", param: "param1"},
{title: "Title2", param: "param2"},
{title: "Title3", param: "param3"}
<ul data-role="listview" data-inset="true">
<li>
<a href="#mypage" onclick="myfunc(param1);">Title1</a>
</li>
<li>
<a href="#mypage" onclick="myfunc(param2);">Title2</a>
</li>
<li>
<a href="#mypage" onclick="myfunc(param3);">Title3</a>
</li>
</ul>
答案 0 :(得分:1)
你可以这样做:
var json = [
{"title": "Title1", "param": "param1", "subMenu": [
{"title": "SubTitle1", "param": "param1-1"},
{"title": "SubTitle2", "param": "param1-2", "subMenu": [
{"title": "SubSubTitle1", "param": "param1-1-1"},
{"title": "SubSubTitle2", "param": "param1-1-2"},
{"title": "SubSubTitle2", "param": "param1-1-3"}
]}
]},
{"title": "Title2", "param": "param2"},
{"title": "Title3", "param": "param3"}
];
var myfunc = function(param) {
alert(param);
};
function makeList(array, root){
if(typeof root === 'undefined'){
root = $('body');
}
var ul = $("<ul></ul>");
root.append(ul);
for (var i = 0; i < array.length; i++) {
var li = $("<li></li>");
ul.append(li);
var a = $("<a href='#' data-param='" + array[i].param + "'>" + array[i].title + "</a>");
li.append(a);
a.click(function() {
alert($(this).data("param"));
});
if(typeof array[i].subMenu !== 'undefined'){
makeList(array[i].subMenu, li);
}
}
}
makeList(json);
您只需遍历json数组并将属性值放在所需的位置,然后使用递归来处理嵌套列表。我把param放在数据attr中以使事情变得更简单。
答案 1 :(得分:-1)
您可以使用jQuery $.each循环遍历数据数组。
var data = [
{title: "Title1", param: "param1"},
{title: "Title2", param: "param2"},
{title: "Title3", param: "param3"}
];
$.each(data, function(index, value) {
var html = '<li><a href="#mypage" onclick="myfunc('+value.param+');">'+value.title+'</a></li>';
$('ul').append(html); // ul could also be a class of the list
});
这将是一个原始的jQuery解决方案。 (未测试)它还使用您的onClick处理程序。