我一直在使用一种工具来为不同国家/地区的用户显示隐藏元素(产品价格)。例如,英国用户将看到与美国用户不同的价格。
我已经解决了这个问题的解决方案
但是,这仅适用于显示价格的目标标题的第一个实例。
我知道每个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();
几点...
class
对于HTML
包含国家/地区代码的元素,请使用,而不是id
。这将允许您一次显示多个元素。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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句