1

我想使用带有函数的纯 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>

这是我的 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"
        }
    }
}
4

1 回答 1

3

所以看起来我没有为复选框添加监听器。这是最终的工作代码

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)
})
于 2020-12-11T03:10:52.050 回答