javascript 使用 Jquery 解析字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15798678/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 02:08:46  来源:igfitidea点击:

Parse String with Jquery

javascriptjquerystringparsing

提问by Mohammad Adil

jsFiddle

js小提琴

I have got a simple select menu containing all countries with their city's listed in respective option value. The value also contains some other data, for instance Canadahas value +1|}|22|Xwhile United Stateshas this +1|}|128|X||{|58$Abilene#|{|59$Akron#|{|1$Alabama#|{|2$Alaska#|{|60$Albany#|....

我有一个简单的选择菜单,其中包含所有国家,其城市列在各自的选项值中。该值还包含一些其他数据,例如Canadahas value +1|}|22|Xwhile United Stateshas this+1|}|128|X||{|58$Abilene#|{|59$Akron#|{|1$Alabama#|{|2$Alaska#|{|60$Albany#|....

I need to fill another select menu on change of country select menu. I can't figure out how can i parse each city listed in the country's value.

我需要在更改国家/地区选择菜单时填写另一个选择菜单。我不知道如何解析该国家/地区值中列出的每个城市。

回答by Hanlet Esca?o

Maybe try this, idk, that data was kind of weird:

也许试试这个,idk,那个数据有点奇怪:

$('#country_residence').on('change', function () {
    var cities = $(this).val().split('$');
    $("#cities option").remove();
    for(var i = 1;i<cities.length;i++)
    {
     var city = String(cities[i]);
        if(city.indexOf("#")>-1)
            city = city.substring(0,city.indexOf("#"));


        $("#cities").append("<option>" + city + "</option>");
    }
});

jsFiddle: http://jsfiddle.net/EyVuS/3/

jsFiddlehttp: //jsfiddle.net/EyVuS/3/

回答by Moby's Stunt Double

Ifthere was absolutely no other way to get cleaner data? I'd do some (albeit somewhat brain-melting) regular expression matching on the server side to filter the information and then parse it into a usable list for use with JSON.

如果绝对没有其他方法可以获得更干净的数据?我会在服务器端做一些(虽然有点费脑筋)正则表达式匹配来过滤信息,然后将它解析成一个可用的列表以与 JSON 一起使用。

I, for one, would not attempt to do this on the client side.

一方面,我不会尝试在客户端执行此操作。