我是 json 的新手,对它一无所知,但看到它的强大功能,我打算切换到它以获得更好的性能。在我的 Web 应用程序中,我有三个不同的下拉列表:轿车、掀背车和 SUV。
我想要,每当用户点击它们中的任何一个时,比如舱口,json 文件中所有舱口的“名称”都会加载到下拉列表中。当用户点击舱口的任何名称时,相应的价格和汽车制造商公司将显示在 html 页面的 id="show"
内容中。
我需要调用什么 jquery 片段来完成这项工作/我应该如何进行。我是 jquery 的新手,对 json 一无所知,所以我将不胜感激
在此先感谢,请查找文件的内容以获得更好的想法。
我的 html 文件的内容(我正在使用 Twitter Bootstrap )
<div id="abc">
<!-- btn-group --> <div class="btn-group"><button type="button" class="btn dropdown-toggle" data-toggle="dropdown">Hatch</button><ul class="dropdown-menu">
<li><a href="#">Hatch names here one below the other</a></li>
<li><a href="#">Next Hatch name here</a></li>
<li><a href="#">Next Hatch name here</a></li>
</ul>
</div><!-- /btn-group -->
<!-- btn-group --> <div class="btn-group"><button type="button" class="btn dropdown-toggle" data-toggle="dropdown">Sedan</button><ul class="dropdown-menu">
<li><a href="#">Sedan names here one below the other</a></li>
<li><a href="#">Next Sedan name here</a></li>
<li><a href="#">Next Sedan name here</a></li>
</ul>
</div><!-- /btn-group -->
<!-- btn-group --> <div class="btn-group"><button type="button" class="btn dropdown-toggle" data-toggle="dropdown">SUV</button><ul class="dropdown-menu">
<li><a href="#">SUV names here one below the other</a></li>
<li><a href="#">Next SUV name here</a></li>
<li><a href="#">Next SUV name here</a></li>
</ul>
</div><!-- /btn-group -->
</div>
<div id="show"><!-- Show the content related to the item clicked in either of the lists here --></div>
我的 json 文件的内容(打算本地存储在网站的根文件夹中)
{
"Hatch": [
{
"name": "Fiesta",
"price": "1223",
"maker": "Ford"
},
{
"name": "Polo",
"price": "3453",
"maker": "VW"
}
],
"Sedan": [
{
"name": "Mustang",
"price": "1223",
"maker": "Ford"
},
{
"name": "Jetta",
"price": "3453",
"maker": "VW"
}
],
"SUV": [
{
"name": "Santa Fe",
"price": "1223",
"maker": "Hyundai"
},
{
"name": "Evoque",
"price": "3453",
"maker": "Land Rover"
}
]
}
最佳答案
为了学习所以好看,这是我的好日子^^^:
Bootstrap :http://bootply.com/113296
JS :
$(document).ready(function(){
for( index in json.Hatch )
{
$('#hatch ul').append('<li><a href="#" data-maker="'+json.Hatch[index].maker+'" data-price="'+json.Hatch[index].price+'">'+json.Hatch[index].name+'</a></li>');
}
for( index in json.Sedan )
{
$('#sedan ul').append('<li><a href="#" data-maker="'+json.Sedan[index].maker+'" data-price="'+json.Sedan[index].price+'">'+json.Sedan[index].name+'</a></li>');
}
for( index in json.SUV )
{
$('#suv ul').append('<li><a href="#" data-maker="'+json.SUV[index].maker+'" data-price="'+json.SUV[index].price+'">'+json.SUV[index].name+'</a></li>');
}
$('a').on('click', function(){
$('#show').html( 'Price : ' + $(this).attr('data-price') + '| Maker : ' + $(this).attr('data-maker') );
});
});
关于javascript - 如何动态地使用 json 数据填充下拉列表(部分分为三个不同的下拉列表)并在单击时遇到操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21747878/