【发布时间】:2013-12-19 00:33:28
【问题描述】:
我正在尝试创建一个搜索框,该搜索框基本上会根据用户输入的 json 文件中的键值对自动完成。看起来使用 datalist 可能是最好的选择,但是当我执行下面的代码时,html 中没有出现任何选项标签。
我对 jquery 和 json 还是很陌生,所以我愿意接受建议。
这是 json。如果相关,该列表包含 1450 项:
{ "osCars": [
{ "id": 1,
"name": "Cadillac",
"type": "Sedan",
"desc": "A fine American automobile"
},
{ "id": 2,
"name": "BWM",
"type": "Sedan",
"desc": "A fine German automobile"
},
{ "id": 3,
"name": "Lexus",
"type": "Sedan",
"desc": "A fine Japanese automobile"
}
]}
这是html:
<input type="text" maxlength="30" list="carList" id="carSearchBox" name="carSearchBox" pattern="[A-Za-z '-]*$" placeholder="search cars" autofocus autocomplete="on">
<datalist id="carList"></datalist>
<script src="js/main.js"></script>
<script>window.onload=getCars;</script>
这里是 javascript/jquery:
function getCars() {
var url, carOption;
url = 'js/cars.json';
$.getJSON(url, function(data) {
//populate the cars datalist
$(data.osCars).each(function() {
carsOption = "<option value=\"" + this.id + "\">" + this.name + "</option>";
$('#carList').append(carsOption);
});
});
}
【问题讨论】:
标签: javascript jquery json html