【问题标题】:How to show or hide element based on an Array of Geo ip如何根据地理 ip 数组显示或隐藏元素
【发布时间】:2015-05-11 19:03:06
【问题描述】:

您好,我希望在 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

【问题讨论】:

  • 你可以使用for循环来循环遍历数组......你知道如何使用for循环吗?

标签: javascript jquery html css arrays


【解决方案1】:

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

【讨论】:

  • 我确实提交了答案,但这要好得多!
猜你喜欢
  • 2021-04-20
  • 2014-09-24
  • 1970-01-01
  • 1970-01-01
  • 2020-11-07
  • 2016-06-11
  • 2021-10-10
  • 2013-01-20
  • 1970-01-01
相关资源
最近更新 更多