我的json文件如下:
var obj = {
Dilse : {"name":"Dil Se Re","length":"5:40","songType":"Romantic"},
Dilse : {"name":"Jiya Jale","length":"3:50","songType":"Self Description"},
Dilse : {"name":"Chaiyya Chaiyya","length":"4:30","songType":"Masti"},
Rockstar : {"name":"Sadda haq","length":"5:40","songType":"Romantic"},
Rockstar : {"name":"Tum ho Pas Mere","length":"3:50","songType":"Self Description"},
Rockstar : {"name":"Sheher me","length":"4:30","songType":"Masti"},
}
我想在点击Dil se时检索Dilse条目,并在点击Rockstar时检索Rockstar条目。我已经在我的页面上有Dilse和Rockstar条目。
JS函数看起来像:
function dilSe(){
document.getElementById("div0").innerHTML = ""; var k =0;
if(xhr.readyState==4){
if(xhr.status==200){
var data=xhr.responseText;
var arr=eval(data);
for(var i=0;i<3;i++){ //I dont know if I should itearte like this !?
var link=document.createElement('a');
link.id='name1'+k++;
link.innerHTML="Song Name: " +obj.Dilse.name+"<br/>"+"Song Length: "+obj.Dilse.length+"<br/>"+"Song Type: "+obj.Dilse.songType+"<br/><br/>";
console.log("link.id is "+link.id);
link.setAttribute('href','#');
link.addEventListener('click',albums[link.id]);
div0.appendChild(link);
}
}else{
div0.innerHTML="Oops, error in communication!";
div0.style.color="red";
}
}
}
function rockStar(){
document.getElementById("div0").innerHTML = ""; var k =0; var r=3;
if(xhr.readyState==4){
if(xhr.status==200){
var data=xhr.responseText;
var arr=eval(data);
for(var i=0;i<3;i++){ //I dont know if I should itearte like this !?
var link=document.createElement('a');
link.id='name2'+k++;
link.innerHTML="Song Name: " +obj.Rockstar.name+"<br/>"+"Song Length: "+obj.Rockstar.length+"<br/>"+"Song Type: "+obj.Rockstar.songType+"<br/><br/>";
console.log("link.id is "+link.id);
link.setAttribute('href','#');
console.log("obj.rockstar.name is "+obj.Rockstar.name);
link.addEventListener('click',albums[link.id]);
div0.appendChild(link);
}
}else{
div0.innerHTML="Oops, error in communication!";
div0.style.color="red";
}
}
}
但最后我得到的是Dilse的最后一个条目(即Chaiyya Chaiyya)和Rockstar的最后一个条目(即Sheher me)。我想要显示所有三个条目。
答案 0 :(得分:1)
您的JSON对象不正确。你显然不能拥有相同键的多个条目(你正在做的是告诉JS:&#34;詹姆斯是这个人。啊不,詹姆斯是另一个人。啊不再,詹姆斯是第三个人&#34;。当然,他只记得最后一个。
您需要使用数组。最简单的解决方案是将您的JSON修改为如下所示:
var obj = {
Dilse :
[
{"name":"Dil Se Re","length":"5:40","songType":"Romantic"},
{"name":"Jiya Jale","length":"3:50","songType":"Self Description"},
{"name":"Chaiyya Chaiyya","length":"4:30","songType":"Masti"},
],
Rockstar :
[
{"name":"Sadda haq","length":"5:40","songType":"Romantic"},
{"name":"Tum ho Pas Mere","length":"3:50","songType":"Self Description"},
{"name":"Sheher me","length":"4:30","songType":"Masti"},
],
}
还有其他可能的选项,例如单个数组(非关联),以及作为每个对象内部值之一的键,但这需要您遍历整个数组以查找所需的内容