【问题标题】:Hide mutliple elements based on Geo ip基于 Geoip 隐藏多个元素
【发布时间】:2019-04-25 07:42:18
【问题描述】:

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

我已经从this question实现了一个解决方案

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

我知道每个 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">$89.95</h4></div>

【问题讨论】:

    标签: jquery html css geolocation


    【解决方案1】:

    要让您的 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">$89.95</h4>
    </div>
    <div class="US">
      <h4 class="h4black">$89.95</h4>
    </div>

    jsFiddle

    【讨论】:

    • 如何调整我的 jQuery 以适应这种情况?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-23
    • 1970-01-01
    • 2021-07-23
    • 2021-03-10
    • 2016-08-03
    相关资源
    最近更新 更多