我需要编写一个代码,我需要根据另一个下拉列表的选择来填充下拉列表,其中需要将下拉列表的值作为数值,但 script.js 不接受任何数字相反,它将其视为十进制值。这个概念很新,请帮我解决这个问题,谢谢
data.json
{
"1": "coke,pepsi",
"2":"chips,biscuit"
}
的index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link rel="stylesheet" href="style.css" />
<script data-require="jquery" data-semver="3.0.0" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
<script src="script.js"></script>
</head>
<body>
<div class="form-group">
<select id="json-one" class="form-control">
<option selected="" value="base">Please Select</option>
<option value="1">Beverages</option>
<option value="2">Snacks</option>
</select>
</div>
<div class="form-group">
<select id="json-two" class="form-control">
<option>Please choose from above</option>
</select>
</div>
</body>
</html>
的script.js
$(function() {
$("#json-one").change(function() {
var $dropdown = $(this);
$.getJSON("data.json", function(data) {
var key = $dropdown.val();
var vals = [];
switch(key) {
case 'beverages':
vals = data['1'].split(",");
break;
case 'snacks':
vals = data['2'].split(",");
break;
case 'base':
vals = ['Please choose from above'];
}
var $jsontwo = $("#json-two");
$jsontwo.empty();
$.each(vals, function(index, value) {
$jsontwo.append("<option>" + value + "</option>");
});
});
});
});
答案 0 :(得分:0)
使用bracket-notation
访问response
对象属性名称可以是任何有效的JavaScript字符串,也可以是可以转换为字符串的任何内容,包括空字符串。但是,任何不是有效JavaScript标识符的属性名称(例如,具有空格或连字符的属性名称,或以数字开头的属性名称)只能使用方括号表示法访问。
另一个问题是,您的option
值为0 or 1
,但在switch
中,您正在使用案例Beverages
和Snacks
对其进行测试,将其更改为{{ 1}}和0
1
$("#json-one").change(function() {
var $dropdown = $(this);
var data = {
"1": "coke,pepsi",
"2": "chips,biscuit"
};
var key = $dropdown.val();
var vals = [];
switch (key) {
case '1':
vals = data['1'].split(",");
break;
case '2':
vals = data['2'].split(",");
break;
case 'base':
vals = ['Please choose from above'];
}
var $jsontwo = $("#json-two");
$jsontwo.empty();
$.each(vals, function(index, value) {
$jsontwo.append("<option>" + value + "</option>");
});
});
简化代码:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="form-group">
<select id="json-one" class="form-control">
<option selected="" value="base">Please Select</option>
<option value="1">Beverages</option>
<option value="2">Snacks</option>
</select>
</div>
<div class="form-group">
<select id="json-two" class="form-control">
<option>Please choose from above</option>
</select>
</div>
$("#json-one").change(function() {
var $dropdown = $(this);
var data = {
"1": "coke,pepsi",
"2": "chips,biscuit"
};
var key = $dropdown.val();
var vals = data[key] ? data[key].split(",") : ['Please choose from above'];
var $jsontwo = $("#json-two");
$jsontwo.empty();
$.each(vals, function(index, value) {
$jsontwo.append("<option>" + value + "</option>");
});
});