使用字符串列表中的值填充<select> </select>

时间:2011-12-23 02:19:38

标签: jquery ajax regex list populate

我有一个字符串列表,用于名为WeatherLocationDatabase.txt的{​​{3}} API,看起来有点像这样:

CityName="Aachen, DE" Location="EUR|DE|GM011|AACHEN" Country="Germany"
CityName="Aalborg, DK" Location="EUR|DK|DA007|AALBORG" Country="Denmark"
CityName="Aalesund, NO" Location="EUR|NO|NO007|AALESUND" Country="Norway"
CityName="Aare, SE" Location="EUR|SE|SW006|AARE" Country="Sweden"
CityName="Aarhus, DK" Location="EUR|DK|DA001|AARHUS" Country="Denmark"
CityName="Aba, NG" Location="AFR|NG|NI008|ABA" Country="Nigeria"
CityName="Abadan, IR" Location="MEA|IR|IR016|ABADAN" Country="Iran"
CityName="Abakan, RU" Location="ASI|RU|RS033|ABAKAN" Country="Russia"
CityName="Abbotsford, CA" Location="NAM|CA|BC|ABBOTSFORD" Country="Canada"
CityName="Abeokuta, NG" Location="AFR|NG|NI000|ABEOKUTA" Country="Nigeria"
CityName="Aberdeen, UK" Location="EUR|UK|UK002|ABERDEEN" Country="United Kingdom"
CityName="Abidjan, CI" Location="AFR|CI|IV002|ABIDJAN" Country="Ivory Coast"
...

有没有办法使用AJAX来填充使用jQuery看起来像这样的<select>

<select>
    <option value="CityName">CityName</option>
    <option value="CityName">CityName</option>
    <option value="CityName">CityName</option>
    <option value="CityName">CityName</option>
    ...
</select>

1 个答案:

答案 0 :(得分:3)

使用该文本文件,您可以使用jQuery并生成:

$.get('WeatherLocationDatabase.txt', function(text){
  var markup = "",
      i, item,
      data = text.split(/CityName="(.+)"\sLocation="(.*)"\sCountry="(.*)"\s?/mg).filter(function(e){return e});
  for( i = 0; item = data[i]; i+=3){
    // no need to specify value if equals to inner text.
    markup += "<option>" + item + "</option>";
    // you could break if data[i+1] or data[i+2] changes
  }
  $("#someSelectID").append(markup);
});

解释var data: 我通过RegEx拆分以匹配CityName,Location和Country值,然后我使用过滤器hack删除RegEx拆分生成的空字符串索引。那时,数据应该如下:

["Aachen, DE", "EUR|DE|GM011|AACHEN", "Germany", "Aalborg, DK", "EUR|DK|DA007|AALBORG", "Denmark", "Aalesund, NO", "EUR|NO|NO007|AALESUND", "Norway", "Aare, SE", "EUR|SE|SW006|AARE", "Sweden", "Aarhus, DK", "EUR|DK|DA001|AARHUS", "Denmark", "Aba, NG", "AFR|NG|NI008|ABA", "Nigeria", "Abadan, IR", "MEA|IR|IR016|ABADAN", "Iran", "Abakan, RU", "ASI|RU|RS033|ABAKAN", "Russia", "Abbotsford, CA", "NAM|CA|BC|ABBOTSFORD", "Canada", "Abeokuta, NG", "AFR|NG|NI000|ABEOKUTA", "Nigeria", "Aberdeen, UK", "EUR|UK|UK002|ABERDEEN", "United Kingdom", "Abidjan, CI", "AFR|CI|IV002|ABIDJAN", "Ivory Coast"]

基本上是:[CityName1, Location1, Country1, CityName2, Location2, Country2, ..., CityNameN, LocationN, CountryN]其中N是行号。

然后我迭代每3个项目(因为有3个属性)

希望这有帮助。