隐藏基于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">$89.95</h4></div>

安迪·霍夫曼

jQuery使用class下面探讨基于方法的工作,请交换此行:

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

有了这个:

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

如果无法使用ES6(或更新的标准),因此无法使用模板文字,则可以使用旧的语法:

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

几点...

  1. class对于HTML包含国家/地区代码元素,请使用,而不是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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章