javascript - 如何根据 Geo ip 数组显示或隐藏元素

标签 javascript jquery html css arrays

你好,我想在 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");

Fiddle

最佳答案

一个简单的 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/

相关文章:

javascript - 如何在 Canvas 上突出显示图像的一部分?

javascript - 如何使用 react js context api 正确存储和检索数据?我的代码没有按预期工作

javascript - 如何在 Javascript 中获取整个 div 的范围偏移量?

javascript - IE 10的JQuery事件mouseenter和mouseleave没有触发,解决方法?

jQuery .text().length() 与 for 循环一起使用

html - 一句话中的多种排版处理?

html - 带有自定义标签的 CSS 宽度

javascript - 为什么我在 Javascript 中计算这个方程时会丢失小数点?

javascript - 根据 Internet 可用性从在线样式表切换到离线样式表

javascript - 附加内容没有获得正确的 CSS 效果