Jquery hide first, or second child element based on geoIP

时间:2017-08-04 12:47:44

标签: jquery geoip

I'd like to hide the the first div if the visitor is from the US and I'd like to hide the second div if the visitor is not from the US. Both div has the same class.

<div class="myclass">from US</div>
<div class="myclass">not from US</div>

I've found some easy implementations with freegeoip.net/json, but I couldn't adapt them to my specific needs.

$.get("http://freegeoip.net/json/", function (response) {
$("#ip").html("IP: " + response.ip);
document.getElementsByClassName(response.country_code)[0].style.display = "none";
}, "jsonp");

2 个答案:

答案 0 :(得分:0)

(function($) {
    $(document).ready(function() {
        var isFromUS = true; // Get the flag from your geoIP service
        $('.myclass').eq(isFromUS ? 0 : 1).hide();
    });
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="myclass">from US</div>
<div class="myclass">not from US</div>

答案 1 :(得分:0)

此时您真正需要做的就是进行ajax调用并阅读响应。由于您使用的是jQuery,因此相对简单:

$.ajax('https://freegeoip.net/json/')
    .done(function (response) {
        var isUS = response.country_code === 'US';
        // Your code to hide/show here.
    });

以下是一个工作示例:https://jsfiddle.net/TheQueue841/ap3tfyf9/4/

我对原始代码做了一些小改动;默认情况下隐藏元素以避免不需要的内容。

请注意:无论出于何种原因,Firefox都会拒绝ajax调用,但它在Chrome中运行良好。因为Firefox有额外的(偶尔不必要的)安全验证,这可能是由于目标服务器上的某些东西。我找不到有效的ip geolocation api,但是否则任何其他api都会以相同的方式工作。只需先查看回复,看看国家/地区代码是如何存储的。

编辑:按位置而不是课程更新目标解决方案。

相关问题