wir*_*dev 2 javascript bootstrap-5
我想用带有函数的纯 Javascript 进行切换。但似乎该函数内的循环不起作用,因为它只能检测默认状态。当我尝试手动设置输入状态时,if-else 语句起作用。但是,如果我点击开关,什么也不会发生。我为此使用 Bootstrap 5 Beta。只要除了引导包 JS 之外不需要框架/库/附加模块,就可以接受任何更好的建议。
这是我的切换 html 代码:
<div class="form-check form-switch mx-3">
<input class="form-check-input" type="checkbox" id="pricingSwitch">
</div>
Run Code Online (Sandbox Code Playgroud)
这是我的 Javascript 函数:
function pricingTable() {
console.log("Called")
var checkbox = document.getElementById('pricingSwitch')
var priceMonthly = document.getElementsByClassName("price-monthly")
var priceAnnual = document.getElementsByClassName("price-annual")
var durationMonth = document.getElementsByClassName("duration-month")
var durationYear = document.getElementsByClassName("duration-year")
console.log("Pre Loop")
for (var i = 0; i < priceMonthly.length; i++) {
console.log(checkbox.checked)
console.log(i)
if (checkbox.checked == true) {
priceMonthly[i].style.display = "none"
priceAnnual[i].style.display = "inline-block"
durationMonth[i].style.display = "none"
durationYear[i].style.display = "inline-block"
} else if (checkbox.checked == false) {
priceMonthly[i].style.display = "inline-block"
priceAnnual[i].style.display = "none"
durationMonth[i].style.display = "inline-block"
durationYear[i].style.display = "none"
}
}
}
Run Code Online (Sandbox Code Playgroud)
所以看来我没有为复选框添加侦听器。这是最终的工作代码
var checkbox = document.getElementById('pricingSwitch')
var priceMonthly = document.getElementsByClassName("price-monthly")
var priceAnnual = document.getElementsByClassName("price-annual")
var durationMonth = document.getElementsByClassName("duration-month")
var durationYear = document.getElementsByClassName("duration-year")
function checker(checked) {
checked ? showAnnual() : showMonthly()
}
function showAnnual() {
priceMonthly[0].style.display = "none"
priceAnnual[0].style.display = "inline-block"
durationMonth[0].style.display = "none"
durationYear[0].style.display = "inline-block"
}
function showMonthly() {
priceMonthly[0].style.display = "inline-block"
priceAnnual[0].style.display = "none"
durationMonth[0].style.display = "inline-block"
durationYear[0].style.display = "none"
}
checker(this.checked)
checkbox.addEventListener('change', function () {
checker(this.checked)
})
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3439 次 |
最近记录: |