我正在尝试创建一个脚本,该脚本将使用JQuery的自动完成文本框来显示已按状态过滤的数组中的县数据。州是一个下拉列表。例如:如果用户为州选择了“Illinois”,则根据他们在文本框中输入的乞讨字母,autocompklete将为他们提供最接近的县名。我成功地能够按状态过滤数组,然后使用正确的数据加载数组,但是我在尝试将数组加载到自动完成时遇到问题。这是代码段。非常感谢你的帮助:
<body >
<script type="text/javascript">
function findCounties(State)
{
var County = new Object();
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp != null)
{
xmlhttp.open("GET","US_Counties.csv",false); // the false makes this synchronous!
xmlhttp.send();
var text = xmlhttp.responseText;
// text contains the ENTIRE CONTENTS of the text file
// you *could* just write those contents directly to the HTML output:
// but you might want to process that one line at a time. if so:
var lines = text.split("\n");
var cntCounty = 0;
for (var n=0; n<lines.length; n++)
{
if(lines[n].indexOf(State) > 0){
var line = lines[n];
var populate = line.split(',');
County[cntCounty] = populate[1];
cntCounty++;
}//IF
}//for
$(function() {
var Counties = [{
a_state: []
};
for(var i in County) {
var item = County[i];
Counties.a_state.push({
"label" : item.County
"value" : item.County`enter code here`
});
];
j$("#counties").autocomplete({
source: Counties
}).data("autocomplete")._renderItem = function(ul, item) {
return $("<li>").data("item.autocomplete", item).append("<a>" + item.label ++ "</a>").appendTo (ul);
});
答案 0 :(得分:0)
我使用了这个javascript代码:
var stateList, countyList;
$(document).ready( function() {
$.ajax({type: "GET",
url: "US_counties.csv", // list of counties
cache: false,
error: function (xhr, textStatus, errorThrown) {
window.alert(textStatus);
},
success: function (text, textStatus, xhr) {
var s1 = $('#s1')[0]; // the select box
stateList = [];
// each line has one county on it
$.each(text.split("\n"), function (ix, elt) {
var items = elt.split(','),
stateName = items[0],
countyName = items[3], a;
if (typeof stateList[stateName] == 'undefined') {
a = [];
a.push(countyName);
stateList[stateName] = a;
// add state to the select box
s1.options[s1.options.length] = new Option(stateName, stateName);
}
else {
stateList[stateName].push(countyName);
}
});
// set the change event handler for the dropdown
$('#s1').bind('change', function() {
countyList = stateList[this.value];
$("#t1") // the text box
.autocomplete({ source: countyList })
.val('');
});
// trigger a 'fake' change, to set up the autocomplete
$('#s1').trigger('change');
}});
});
说明:stateList
是列表清单。该列表的内部索引是州名,或者在我的例子中,是州名缩写(AL,AK,AZ等)。 stateList
中的每个项目都是字符串列表,每个字符串都是该州的县名。
代码的作用:
stateList
,并将该状态添加到下拉列表中。将县添加到该州的县列表中。还将更改事件处理程序绑定到下拉列表。 编辑 - 仅供参考,我从this list获得了县名单,只是用逗号替换了标签。用逗号替换选项卡不是必需的,但它使我更容易在文本编辑器中浏览列表。如果您不用逗号替换制表符,则需要修改对elt.split()
的调用以拆分制表符。