我正在向 ipinfo API 发出 .get
请求以获取国家/地区代码,然后小写字符串并将其解析为应获取国家/地区代码的第二个函数(例如:us)并显示基于 ISO 3166-1 alpha-2 的标志。
虽然countrySelect()
似乎忽略了我的国家变量。
默认国家/地区在页面加载时设置(“gb”),但随后我的回调应该覆盖它。
知道发生了什么吗?
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: []
});
最佳答案
根据documentation ,与“selectCountry”一起使用时,countrySelect 方法采用字符串。不需要像这样引用字符串:
country = "'"+lusercountry+"'";
只需按原样传递 lusercountry
即可。即
$("#country_selector").countrySelect("selectCountry", lusercountry);
关于javascript - 解析异步回调中的 var,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41060772/