0

我正在尝试创建一个脚本,该脚本将使用 JQuery 的自动完成文本框来显示已按州过滤的数组中的县数据。状态是一个下拉列表。例如:如果用户选择了“伊利诺伊州”作为州,根据他们在文本框中输入的乞求字母,自动补全会为他们提供最接近的县名。我成功地能够按状态过滤数组,然后用正确的数据加载数组,但我在尝试将数组加载到自动完成时遇到问题。这是代码段。非常感谢您的帮助:

    <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);
});
4

1 回答 1

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、A​​Z 等)。中的每一项stateList都是字符串列表,每一项都是该州的县名。

代码的作用:

  • 为文档就绪事件注册一个函数。
  • 在该函数中,通过 ajax 获取县列表的 CSV。
  • 在该 ajax 调用的成功回调中,解析结果。对于每个新状态,向 中添加一个项目stateList,然后将该状态添加到下拉列表中。将该县添加到该州的县列表中。还将更改事件处理程序绑定到下拉列表。
  • 在更改处理程序中,将自动完成应用于“县名”文本框。来源是下拉列表中所选州的县名列表。

编辑- 仅供参考,我从这个列表中得到了县列表,只是用逗号替换了制表符。用逗号替换制表符不是必需的,但它使我更容易在文本编辑器中浏览列表。如果您不用逗号替换制表符,那么您需要修改对制表符的调用elt.split()以拆分制表符。

于 2012-04-17T05:00:59.130 回答