(1)data.json
{
"species":[
{"specy":"水果","Sid":"1"},
{"specy":"蔬菜","Sid":"2"},
{"specy":"肉类","Sid":"3"}
],
"name":[
{"nam":"苹果","Sid":"1","Nid":"1","Price":"3"},
{"nam":"葡萄","Sid":"1","Nid":"2","Price":"10"},
{"nam":"黄瓜","Sid":"2","Nid":"3","Price":"2"},
{"nam":"白菜","Sid":"2","Nid":"4","Price":"1"},
{"nam":"猪肉","Sid":"3","Nid":"5","Price":"15"},
{"nam":"鸡肉","Sid":"3","Nid":"6","Price":"9"}
]
}
(2)js
$(function() {
$.ajax({
url: 'data/data.json', //文件的路径 (也可以是网址)
type: 'get',
dataType: 'json',
async: false, //同步(同时触发,互不影响)、异步(先执行ajax,然后执行下一步)
success: function(res) { //回掉函数:成功
//渲染数据
speciesFun(res);
nameFun(res);
changeEvent(res);
submitFun(res);
},
error: function(res) { //回调函数:失败
alert('error')
}
})
//商品种类
function speciesFun(res) {
var speStr = '';
for(var i = 0; i < res.species.length; i++) {
speStr += "<option value='" + res.species[i].Sid + "'>" + res.species[i].specy + "</option>";
}
$("#species").html(speStr);
}
//种类类别
function nameFun(res) {
var nameS = "";
for(var i = 0; i < res.name.length; i++) {
if($("#species").val() == res.name[i].Sid) {
nameS += "<option value='" + res.name[i].Nid + "'>" + res.name[i].nam + "</option>";
}
}
$("#name").html(nameS);
var index = $("#name").val() - 1
$("#price").html("单价为:" + res.name[index].Price + "元");
}
//计算总价
function countFun(res){
var index = $("#name").val() - 1
$("#total").html("总价为:" + $("#count").val() * res.name[index].Price + "元");
}
//改变种类,类别做出变化
function changeEvent(res) {
$("#species").change(function() {
nameFun(res);
countFun(res);
$("#total").html("")
("#count").val()==""
})
$("#name").change(function() {
var index = $("#name").val() - 1
$("#price").html("单价为:" + res.name[index].Price + "元");
$("#total").html("")
("#count").val()==""
})
}
//根据用户输入的值进行计算总价
function submitFun(res) {
$("#submit").click(function() {
//获取当前品类的ID 并减一作为索引下标
str=$("#count").val()
if (str.length>0){
if($("#count").val()=="0"){
alert("购买数量为0!")
}
else{
countFun(res);
}
}
else{
alert("未输入购买数量!")
}
})
}
})
(3)index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<h1>购物车</h1>
数量:<input placeholder="请输入购买数量" type="text" id="count" class="count"/><br />
种类:<select id="species"></select><br />
品种:<select id="name"></select><br />
<input type="button" id="submit" value="提交" />
<p id="price"></p>
<p id="total"></p>
</body>
<script type="text/javascript" src="js/jquery1.7.js" ></script>
<script type="text/javascript" src="js/index.js" ></script>
</html>