如何使用纯 Javascript 检查 Switch 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>

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

        }

    }

}


米脂
浏览 92回答 1
1回答

慕运维8079593

所以看来我没有为复选框添加侦听器。这是最终的工作代码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) {&nbsp; checked ? showAnnual() : showMonthly()}function showAnnual() {&nbsp; priceMonthly[0].style.display = "none"&nbsp; priceAnnual[0].style.display = "inline-block"&nbsp; durationMonth[0].style.display = "none"&nbsp; durationYear[0].style.display = "inline-block"}function showMonthly() {&nbsp; priceMonthly[0].style.display = "inline-block"&nbsp; priceAnnual[0].style.display = "none"&nbsp; durationMonth[0].style.display = "inline-block"&nbsp; durationYear[0].style.display = "none"}checker(this.checked)checkbox.addEventListener('change', function () {&nbsp; checker(this.checked)})
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript