所以我有一个简单的页面,它有一个更简单的javaScript计数器。我想这三个div中的减号和加号,当你点击它们时,它们会递增和递减。一旦它们被点击,它们将用count类更新span的内容。
但是,当我单击减号和减号时,它们都是递增的。我实现了一个for循环,它将检查值以防止这种情况,但它不起作用。计数器也显示负值,我该怎么做才能解决这个问题?
const ctaLabels = document.querySelectorAll(".cta");
Array.from(ctaLabels).forEach(function (label) {
label.addEventListener("click", function () {
const countSpan = label.parentNode.parentNode.querySelector(".count");
if (label.textContent === "+") {
countSpan.textContent = parseInt(countSpan.textContent) + 1;
} else {
countSpan.textContent = parseInt(countSpan.textContent) - 1;
}
});
});
.cta {
color: white;
background: blue;
font: var(--font-variant-6);
letter-spacing: 0.5px;
transition: all 0.15s linear;
}
.cta:hover {
background: blue;
cursor: pointer;
transition: all 0.15s linear;
}
<section id="attendees">
<div class="container">
<h3 class="title">How many people should we be expecting?</h3>
<div class="field-group --advanced">
<div class="field --counter --required">
<div class="label">Men:</div>
<div class="input">
<div>
<span class="count">0</span>
</div>
</div>
<div class="actions">
<label for="" class="cta">
<span>−</span>
</label>
<label for="" class="cta">
<span>+</span>
</label>
</div>
<label for="" class="field__label">Men:</label>
<input
required
id="men"
name="men"
type="number"
placeholder="0"
class="field__input"
/>
</div>
<div class="field --counter --required">
<div class="label">Women:</div>
<div class="input">
<div>
<span class="count">0</span>
</div>
</div>
<div class="actions">
<label for="" class="cta">
<span>−</span>
</label>
<label for="" class="cta">
<span>+</span>
</label>
</div>
<label for="" class="field__label">Women:</label>
<input
required
id="women"
name="women"
type="number"
placeholder="0"
class="field__input"
/>
</div>
<div class="field --counter --required">
<div class="label">Children:</div>
<div class="input">
<div>
<span class="count">0</span>
</div>
</div>
<div class="actions">
<label for="" class="cta">
<span>−</span>
</label>
<label for="" class="cta">
<span>+</span>
</label>
</div>
<label for="" class="field__label">Children:</label>
<input
required
id="children"
name="children"
type="number"
placeholder="0"
class="field__input"
/>
</div>
</div>
</div>
</section>
3条答案
按热度按时间wnvonmuf1#
使用trim函数检查是否要-或+,因为文本内容也包含空格
u5rb5r592#
您需要修剪textContent。
2lpgd9683#
问题是,您正在检查
label.textContent
,但查看您的html结构,还有一个span
嵌套在label
标记下。所以label.textContent
永远不会是+/-,你的if语句总是会在else分支上递减数字。您应该更改if语句以检查以下内容:
或者可以从
label
中删除span