基于 Geoip 隐藏多个元素

Hide mutliple elements based on Geo ip

我一直在实施一种工具来为不同国家/地区的用户显示隐藏元素(产品价格)。例如英国用户将看到与美国用户不同的价格。

我已经实施了

的解决方案

但是,这仅适用于显示价格的目标标题的第一个实例。

我知道每个 id 应该是唯一的,但我不知道如何在不为每个产品复制 JQuery 代码的情况下做到这一点,有没有有效的方法可以帮助我?

    $.get("http://freegeoip.app/json/", function (response) {
      $("#ip").html("IP: " + response.ip);
                          

    $("#country_code").html(response.country_code);
                          

    if(response.country_code=='GB'||response.country_code=='US'){
                            

    document.getElementById(response.country_code).style.display = "block";
    }
    }, "jsonp");
    #US { 
      text-align: left; 
      color: black; 
      display:none;
    }
 
    #GB { 
      text-align: left; 
      color: black; 
      display:none;
    } 
    
    
    #ip{
      display:none;
      color:white;
    }

    #country_code{
      display:none;
      color:white;
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="ip">Loading...</div>
    <div id="country_code"></div>
    <div id="GB"><h4 class="h4black">£69.99</h4></div>
    <div id="US"><h4 class="h4black">.95</h4></div>

要让您的 jQuery 使用下面探讨的基于 class 的方法,请换行:

document.getElementById(response.country_code).style.display = "block";

有了这个:

$(`.${response.country_code}`).show();

如果您无法使用 ES6(或更新的标准),因此 template literals,您可以使用旧语法:

$('.' + response.country_code).show();

几点……

  1. 对包含国家/地区代码的 HTML 元素使用 class,而不是 id。这将允许您一次显示多个元素。
  2. 既然您使用的是 jQuery,您不妨使用它为 DOM 查找提供的内置函数。

这是一个证明这些观点的例子:

$(".US").show();
.US,
.GB {
  text-align: left;
  color: black;
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="GB">
  <h4 class="h4black">£69.99</h4>
</div>
<div class="US">
  <h4 class="h4black">.95</h4>
</div>
<div class="US">
  <h4 class="h4black">.95</h4>
</div>

jsFiddle