Javascript If语句检查全局变量,但同时运行这两个条件
我的头撞到墙上了,请帮帮我:( 编辑:该脚本在JSFIDLE(我自己的服务器)上工作,但在客户机的服务器上不工作:/ 我有一个基于全局变量的简单价格切换器。我想使用全局变量,因为切换器包含:文本即折扣(可点击)、样式化复选框(带颜色)、文本(可点击)即打折-这样我可以将侦听器添加到带有文本的可单击Javascript If语句检查全局变量,但同时运行这两个条件,javascript,Javascript,我的头撞到墙上了,请帮帮我:( 编辑:该脚本在JSFIDLE(我自己的服务器)上工作,但在客户机的服务器上不工作:/ 我有一个基于全局变量的简单价格切换器。我想使用全局变量,因为切换器包含:文本即折扣(可点击)、样式化复选框(带颜色)、文本(可点击)即打折-这样我可以将侦听器添加到带有文本的可单击span元素中,并更改设置样式的复选框的颜色等 折扣按钮的代码: <p class="prices-starter-switch"> <span class="prices-start
span
元素中,并更改设置样式的复选框的颜色等
折扣按钮的代码:
<p class="prices-starter-switch">
<span class="prices-starter-discount active">Prices with discount</span>
<label id="pricesSwitcher" class="switch"><input type="checkbox" checked>
<span class="slider round"></span></label>
<span class="prices-starter-discount-none">Prices without discount</span>
</p>
我做错了什么?弄明白了
document.getElementById('prices-switcher').onclick = function() {
if (pricesSetToDiscounted == true) {
pricesShowNormal();
} else {
pricesShowDiscounted();
}
return false;
}
在JSFIDLE、我的服务器和客户机的服务器上都能很好地工作:)我不太确定您想要实现什么,但对我来说,您的代码是有效的。我已经做了一个快速操作。它不能同时执行if..else
的两个分支。很可能再次触发您的单击事件@Nerdkowski-它在JSFIDLE上工作,在live server上不。。。if..else
运行时不查看条件:(
window.pricesSetToDiscounted = true;
// I'm setting the global var to true, since from the backend side I'm showing the client the discounted prices
as he load's the website
window.prices_to_be_calculated = document.querySelectorAll(".price-to-add-discount");
// selecting all the elements with prices to work with
var btn = document.getElementById('pricesSwitcher'); // my simple button ID
btn.addEventListener('click', function() {
if(typeof pricesSetToDiscounted != 'undefined' && pricesSetToDiscounted==true) {
pricesShowNormal();
}
else if(typeof pricesSetToDiscounted != 'undefined' && pricesSetToDiscounted==false) {
pricesShowDiscounted();
}
}, false);
function pricesShowDiscounted() {
var i;
for (i = 0; i < prices_to_be_calculated.length; i++) {
var discountedPrice = prices_to_be_calculated[i].dataset.discountedprice;
prices_to_be_calculated[i].innerHTML = discountedPrice; }
pricesSetToDiscounted = true;
console.log("pricesSetToDiscounted has value: "+pricesSetToDiscounted);
};
function pricesShowNormal() {
var y;
for (y = 0; y < prices_to_be_calculated.length; y++) {
var normalPrice = prices_to_be_calculated[y].dataset.normalprice;
prices_to_be_calculated[y].innerHTML = normalPrice;
}
pricesSetToDiscounted = false;
console.log("pricesSetToDiscounted has value: "+pricesSetToDiscounted);
};
document.getElementById('prices-switcher').onclick = function() {
if (pricesSetToDiscounted == true) {
pricesShowNormal();
} else {
pricesShowDiscounted();
}
return false;
}