[英]Parsing var in async callback
I'm making a .get
request to the ipinfo API to obtain the country code, then lowercase the string and parse it to a second function which should pickup the country code (example: us) and display the flag based on ISO 3166-1 alpha-2. 我正在向ipinfo API发出.get
请求以获取国家/地区代码,然后将字符串小写并将其解析为第二个函数,该函数应提取国家/地区代码(例如:我们)并根据ISO 3166-1显示标志α-2。
Although countrySelect()
seems to be ignoring my country variable. 尽管countrySelect()
似乎忽略了我的国家/地区变量。
A default country gets set on page load ('gb'), but then my callback should overwrite that. 默认国家/地区设置了页面加载('gb'),但随后我的回调应覆盖该国家/地区。
Any idea of what's going on? 有什么想法吗?
var country;
$.get("https://ipinfo.io/country", function(data) {
var usercountry = data; // gets .country = ip location
lusercountry = usercountry.toLowerCase(); // ie. GB to gb
lusercountry = lusercountry.replace(/\s+/g, ''); // takes additional space off the string
country = "'" + lusercountry + "'"; // adds '' to the .country string
$("#country_selector").countrySelect("selectCountry", country);
});
$("#country_selector").countrySelect({
defaultCountry: 'gb',
//preferredCountries: []
});
According to the documentation , the method countrySelect takes a string when used with "selectCountry". 根据文档 ,方法countrySelect与“ selectCountry”一起使用时将使用字符串。 There is no need to quote the string like this: 无需引用这样的字符串:
country = "'"+lusercountry+"'";
Simply pass lusercountry
as is. 只需lusercountry
原样传递lusercountry
。 ie 即
$("#country_selector").countrySelect("selectCountry", lusercountry);
just pass usercountry to countrySelect, and you can minify your cod like that 只需将用户国家/地区传递给countrySelect,就可以像这样缩小鳕鱼
var usercountry = data.toLowerCase().trim();
$("#country_selector").countrySelect("selectCountry", usercountry);
Use trim() instead of replace, there is only one additional space at the end, trim do the job 使用trim()而不是replace,最后只有一个额外的空间,trim做这项工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.