【发布时间】:2020-02-16 13:17:26
【问题描述】:
我的头撞墙了,请帮忙:(
编辑:脚本在我自己的服务器 jsfiddle 上工作,但在客户端的服务器上却不行:/
我有一个基于全局变量的简单价格切换器。我想使用全局变量,因为切换器包含:文本即。折扣(可点击),样式复选框(带颜色),文本(可点击),即。折扣 - 这样我就可以将听众添加到带有文本的可点击 span 元素并更改样式 checkbox 的颜色等。
折扣按钮代码:
<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>
价格元素的构造如下:
<em data-normalprice="52" data-discountedprice="47" class="price-to-add-discount">47</em>
<em data-normalprice="60" data-discountedprice="54" class="price-to-add-discount">54</em>
<em data-normalprice="100" data-discountedprice="90" class="price-to-add-discount">90</em>
data-normalprice 和 data-discountedprice 在 em 元素中保存要交换的价格值。
价格以两种方式列出 - 正常列表和页面底部的表格。所有要切换的价格(正常价格和折扣价)都有price-to-add-discount
在后端,我在页面加载时显示折扣价。
我想使用全局变量来更改所有价格(如em's 和内部table)。
我编写了代码,但是当点击触发监听器时,if 语句一直运行并且不检查条件:/
这是 JS 代码:
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);
};
我做错了什么?
【问题讨论】:
-
我不太确定你想达到什么目标,但对我来说你的代码是有效的。我做了一个快速的jsfiddle。
-
它不能同时执行
if..else的两个分支。你的点击事件很可能再次被触发......!跨度> -
@Nerdkowski - 它可以在 jsfiddle 上运行,但在实时服务器上却不行……
if..else在不查看条件的情况下运行 :(
标签: javascript