如何显示或基于GEO IP的数组元素隐藏 [英] How to show or hide element based on an Array of Geo ip

查看:102
本文介绍了如何显示或基于GEO IP的数组元素隐藏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨我期待在JS if语句做了一个,我想在我的HTML说你好欧洲如果来访的IP是来自欧洲。

Hi I am looking to do an if statement in JS, I want to say "Hello Europe" in my html if the visiting IP is from 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 应该做的很好这里。

A simple indexOf should do nicely here.

$.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");

链接文档进一步阅读:<一href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf\" rel=\"nofollow\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

这篇关于如何显示或基于GEO IP的数组元素隐藏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆