我正在尝试从json文件中实现一个数组项列表,更多列出你在google plus上找到的列表,但我是编程的新手,不知道如何使用javascript.Please help.I试过以下但我得到一个空白页;
ArrayList<Animal> myanimals = new ArrayList<Animal>();
Cat myCat = new Cat();
myanimals.add(myCat);
System.out.println("" + myanimals.get(0).getClass());
Dog newdog = myanimals.get(0); // <-- this would be runtime exception if Java compiler allowed this
和html:
var records = {
"states": [
{
"name": "johor",
"command": "view_johor"
},
{
"name": "selangor",
"command": "view_selangor"
},
{
"name": "melaka",
"command": "view_melaka"
},
{
"name": "kuala lumpur",
"command": "view_kl"
},
{
"name": "penang",
"command": "view_penang"
}
]
};
$.each(records.states, function (key, val) {
$('#ul').append($('<li>').text('name: ' + val.name + ', command: ' + val.command));
});
我不明白list.js和data.js如何作为列表插件工作。我设法使用把手从json文件显示一个列表,但放弃了一路,因为我无法弄清楚所选项目的onclick项目显示内容在handlebars.Now我试图用老式的方式,使用JavaScript。
答案 0 :(得分:1)
您在示例中使用了each()
函数,但未标记jQuery
。这是一个如此简单的案例,我建议你使用纯JavaScript。
var records = {states:[{name:"johor",command:"view_johor"},{name:"selangor",command:"view_selangor"},{name:"melaka",command:"view_melaka"},{name:"kuala lumpur",command:"view_kl"},{name:"penang",command:"view_penang"}]},
elem = document.getElementById('ul'); //get 'ul' element from the DOM
records.states.forEach(function(v) { //iterate over array in JSON
var li = document.createElement('li'); //create 'li' element
li.innerHTML = 'name: ' + v.name; //assign your data to each 'li'
elem.appendChild(li); //append 'li' to the 'ul' element
});
var elems = document.getElementsByTagName('li');
Array.from(elems).forEach((v,i) => v.addEventListener('click', function(){
Array.from(elems).forEach((c,k) => {c.style.background = 'transparent'; c.innerHTML = 'name: ' + records.states[k].name;});
this.innerHTML = 'name: ' + records.states[i].name + ', command: ' + records.states[i].command;
this.style.background = '#E3F6CE';
}));
<ul id="ul"></ul>