亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用純 Javascript 檢查 Switch Bootstrap 5

如何使用純 Javascript 檢查 Switch Bootstrap 5

米脂 2023-11-11 15:53:43
我想用帶有函數的純 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"        }    }}
查看完整描述

1 回答

?
慕運維8079593

TA貢獻1876條經驗 獲得超5個贊

所以看來我沒有為復選框添加偵聽器。這是最終的工作代碼


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)

})


查看完整回答
反對 回復 2023-11-11
  • 1 回答
  • 0 關注
  • 156 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號