gpt4 book ai didi

javascript - 访问 json,将变量名称作为字符串传递

转载 作者:行者123 更新时间:2023-11-28 00:24:23 24 4
gpt4 key购买 nike

我的页面中包含一些 json 文件,如下所示:

<script type="text/javascript" language="javascript" src="json/divaniModerni.json"></script>
<script type="text/javascript" language="javascript" src="json/divaniClassici.json"></script>

它们都具有相同的结构,包含不同的元素:

var divaniModerni = {
"modelli": [
{
"nome": "California",
"num": "5",
},
{
"nome": "Terra",
"num": "6",
},
{
"nome": "Laura",
"num": "7",
},
{
"nome": "Nonstop",
"num": "11",
},
{
"nome": "Venere",
"num": "8",
},
{
"nome": "Comfort",
"num": "5",
},
{
"nome": "Infinity",
"num": "8",
},
]

}

我现在可以像这样解析文件:

$(divaniModerni.modelli).each(function(index, element){ (...) }

但是可以动态地更改文件以解析将名称传递给函数,就像这样?

function show(category)
{
$(category.modelli).each(function(index, element){ (...) }
}

show(divaniModerni);

我尝试过:

$(window[category].modelli).each(function(index, element){ (...) }

但是它不起作用......

编辑:

在每个内部,我根据所选的 json 元素动态地在表格上创建一行:

$(divaniModerni.modelli).each(function(index, element){
if (i == 1)
riga += "<tr>";
riga += "<td><figure><a class='anteprime' rel='prettyPhoto[gallery" + i + "]' href='images/divani/" + element.nome + ".jpg'><img src='images/anteprima/divani/" + element.nome + ".jpg' alt='" + element.nome + "'></a><div class='descrizione'>" + element.nome;
if (element.num > 0)
{
for (j = 2; j <= element.num; j++)
{
riga += "<a style='display:none;' class='anteprime' rel='prettyPhoto[gallery" + i + "]' href='images/divani/" + element.nome + j + ".jpg'><img src='images/anteprima/divani/" + element.nome + j + ".jpg' alt='" + element.nome + "'></a>";
}
}
riga += "</div></figure></td>";
if (i == categoria.modelli.length)
{
riga += "</tr>";
$('#mostra').append(riga);
}
else if (i % 4 == 0)
{
riga += "</tr>";
$('#mostra').append(riga);
riga = "<tr>";
}
i++
})

最佳答案

将对象引用直接传递到each 语句中以仅对其进行迭代。

http://jsfiddle.net/b3zdahc0/

var divaniModerni = {
"modelli": [
{
"nome": "California",
"num": "5",
},
{
"nome": "Terra",
"num": "6",
},
{
"nome": "Laura",
"num": "7",
},
{
"nome": "Nonstop",
"num": "11",
},
{
"nome": "Venere",
"num": "8",
},
{
"nome": "Comfort",
"num": "5",
},
{
"nome": "Infinity",
"num": "8",
}
]
};

function show(category)
{
$.each(category.modelli, function(index, element) {
alert(index)
});

}

$("button").on("click", function(e) {
show(divaniModerni);
});

关于javascript - 访问 json,将变量名称作为字符串传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29703563/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com