你好,我想在 JS 中做一个 if 语句,如果访问的 IP 来自欧洲,我想在我的 html 中说“Hello Europe”。
CSS
#US { text-align: left; color: blue; display:none;}
#CA { text-align: left; color: blue; display:none;}
#World { text-align: left; color: blue; display:none;}
#Europe { text-align: left; color: blue; display:none;}
HTML
<div id="ip">Loading...</div>
<div id="country_code"></div>
<div id="CA">Hello Canada</div>
<div id="US">Hello USA</div>
<div id="World">Hello World</div>
<div id="Europe">Hello Europe</div>
JS
$.get("http://freegeoip.net/json/", function (response) {
$("#ip").html("IP: " + response.ip);
$("#country_code").html(response.country_code);
var country = response.country_code;
var europe = ['AL','AD','AT','BY','BE','BA','BG','HR','CY','CZ','DK','EE','FO','FI','FR','DE','GI','GR','HU','IS','IE','IT','LV','LI','LT','LU','MK','MT','MD','MC','NL','NO','PL','PT','RO','RU','SM','RS','SK','SI','ES','SE','CH','UA','VA','RS','IM','RS','ME'];
if(country == 'US' || country == 'CA') document.getElementById(country).style.display = "block";
else if (country === 'europe')
document.getElementById('Europe').style.display = "block";
else
document.getElementById('World').style.display = "block";
}, "jsonp");
最佳答案
一个简单的 indexOf
应该在这里做得很好。
$.get("http://freegeoip.net/json/", function(response) {
$("#ip").html("IP: " + response.ip);
$("#country_code").html(response.country_code);
var country = response.country_code;
var europe = ['AL', 'AD', 'AT', 'BY', 'BE', 'BA', 'BG', 'HR', 'CY', 'CZ', 'DK', 'EE', 'FO', 'FI', 'FR', 'DE', 'GI', 'GR', 'HU', 'IS', 'IE', 'IT', 'LV', 'LI', 'LT', 'LU', 'MK', 'MT', 'MD', 'MC', 'NL', 'NO', 'PL', 'PT', 'RO', 'RU', 'SM', 'RS', 'SK', 'SI', 'ES', 'SE', 'CH', 'UA', 'VA', 'RS', 'IM', 'RS', 'ME'];
var inEU = europe.indexOf(country) !== -1;
if (country == 'US' || country == 'CA') document.getElementById(country).style.display = "block";
else if (inEU)
document.getElementById('Europe').style.display = "block";
else
document.getElementById('World').style.display = "block";
}, "jsonp");
链接到文档以进一步阅读:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
关于javascript - 如何根据 Geo ip 数组显示或隐藏元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30175630/