【发布时间】:2019-09-26 02:31:42
【问题描述】:
我试图在设定的时间范围内(18.00 和 24.00 之间)使用 Jquery 在我们的 lightspeed 电子商务网站上隐藏几个付款选项,并且仅适用于居住在荷兰的人。
由于我无法更改结帐页面的文件,因此我使用 document.querySelector("#gui-checkout-shipment-methods > div:nth-child(1) > div") 来更改提到的 div 的“css” display:block" 设置为 "display:none"。
我尝试将代码包装在 ajaxSuccess 和 ajaxComplete 函数中,但它没有改变任何东西。
$( document ).ajaxSuccess(function () {
$.get("https://freegeoip.app/json/", function (response) {
$("#ip").html("IP: " + response.ip);
$("#country_code").html(response.country_code);
var currentTime = new Date().getHours();
if(response.country_code=='NL' && 17 <= currentTime&¤tTime < 24){
document.querySelector("#gui-checkout-shipment-methods > div:nth-child(1) > div").style.display = 'none';
document.querySelector("#gui-checkout-shipment-methods > div:nth-child(2) > div").style.display = 'none';
document.querySelector("#gui-checkout-shipment-methods > div:nth-child(3) > div").style.display = 'none';
document.querySelector("#gui-checkout-shipment-methods > div:nth-child(4) > div").style.display = 'none';
document.querySelector("#gui-checkout-shipment-methods > div:nth-child(5) > div").style.display = 'none';
}
if(response.country_code=='NL' && 24 <= currentTime&¤tTime < 17){
document.querySelector("#gui-checkout-shipment-methods > div:nth-child(1) > div").style.display = 'block';
document.querySelector("#gui-checkout-shipment-methods > div:nth-child(2) > div").style.display = 'block';
document.querySelector("#gui-checkout-shipment-methods > div:nth-child(3) > div").style.display = 'block';
document.querySelector("#gui-checkout-shipment-methods > div:nth-child(4) > div").style.display = 'block';
document.querySelector("#gui-checkout-shipment-methods > div:nth-child(5) > div").style.display = 'block';
}
}, "jsonp");});
它工作正常,但只要单击 Ajax 表单单选按钮,我的代码就会停止工作。检查员说:css-change-by-time.js?20190925175433:8 Uncaught TypeError: Cannot read property 'style' of null
这是有道理的,因为我猜在进行 ajax 调用之后,曾经是 display:block 的 div 不再存在,因此它会发生冲突并引发错误。
我在互联网上搜索了一整天,但找不到有效的解决方案。
所以我的实际问题是:
无论发生什么,我如何应用这些更改以及如何使它们保持不变。
【问题讨论】:
-
最好的方法是在应用更改之前检查元素是否存在。这是一个类似问题的链接,您可以应用该解决方案。该解决方案将 jQuery 用于 dom 选择器,您应该使用它,因为您已经在加载它。 stackoverflow.com/questions/32995297/…
-
对你来说,这看起来像下面, if($("#gui-checkout-shipment-methods > div:nth-child(1) > div").length) $("# gui-checkout-shipment-methods > div:nth-child(1) > div").css('display', 'none');
-
如果元素不存在怎么办?
-
如果元素不存在,我给你的代码行将处理。因为如果它不存在,if 语句将评估为 false,并且它不会尝试将样式应用于不存在的元素。
-
另外,我认为您的第二个 if 语句永远不会评估为 true。 currentTime 不能大于 24 且小于 17。这可能会导致您出现问题。
标签: javascript jquery ajax