我是jquery的新手,我希望根据所选选项将url加载到getJSON函数,然后将json数据加载到表中.json文件位于文件夹/ json < br />
例如:如果我在选择选项菜单中选择职员,我希望网址为“json / clerk.json”。
这个代码不正确,但是getJson只是变量url保持为null,这是变量范围问题。
基本上到目前为止,jquery已经尝试过了: BR />
$(document).ready(function() {
var url = null; //url for the getJson function
function employeeType()
{
$('#user').change(function() {
/* setting currently changed option value to option variable */
var option = $(this).find('option:selected').val();
console.log(option);
switch (option) {
case "accountant":
url = "json/accountant.json";
return url;
break;
case "clerk":
url = "json/clerk.json";
return url;
break;
case "admin":
url = "json/administration.json";
return url;
break;
default:
url = "null";
return url;
break;
}
});
}
url = employeeType();
console.log(url); //the url here is null
//this is working url = "json/administration.json";
$.getJSON(url, function(data) {
//table to load json file
var table = $('#myTable tbody');
//loop through the json file
$.each(data, function(key, value) {
console.log(key + " : " + value);
if (key == "ict-skills") {
var ictRow = '<tr class="info"><td colspan="3"><label>ii) ICT Skills</label></td></tr>';
table.append(ictRow);
$.each(value, function(key1, value1) {
for (k in value1) {
// console.log( key1 + ':' + k + ':' + value1[k]);
var row = '<tr><td>' + value1[k] +
'</td><td class="check"><input type="checkbox" class="styled " name="ict[' + k + ']" value="possess"/>' +
'</td><td class="check"><input type="checkbox" class="styled" name="ict[' + k + ']" value="train"/></td>' +
'</tr>';
//console.log(row);
table.append(row);
}
});
}
}
});
选择的html是:
<div class="form-group">
<label class="col-sm-2 control-label">Employee ID</label>
<div class="col-sm-2">
<input type="text" class="form-control" name="id_no">
</div>
<label class="col-sm-2 control-label">Employee Type</label>
<div class="col-sm-2">
<select class="form-control" name="user" id="user">
<option value=""></option>
<option value="accountant">Accountant</option>
<option value="admin">Administration</option>
<option value="clerk">Clerk</option>
</select>
</div>
</div>
答案 0 :(得分:1)
似乎是一个范围问题,请尝试下面的内容(为简洁起见,删除了您的ajax调用):
var employeeType = function (option) {
/* setting currently changed option value to option variable */
switch (option) {
case "accountant":
url = "json/accountant.json";
return url;
break;
case "clerk":
url = "json/clerk.json";
return url;
break;
case "admin":
url = "json/administration.json";
return url;
break;
default:
url = "null";
return url;
break;
}};
$('#user').change(function(){
var option = $(this).find('option:selected').val();
url = employeeType(option);
alert(url);
});
编辑:小提琴 - &gt; https://jsfiddle.net/54y171u9/