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

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

如何使用 JavaScript 在特定單選按鈕上應用條件

如何使用 JavaScript 在特定單選按鈕上應用條件

慕森卡 2023-07-20 17:39:56
我想要的是,當我單擊特定的紅色id 單選按鈕時,它會向我顯示警報,正如您在代碼中看到的那樣...在我的情況下,它沒有發生...問題是什么以及如何對此進行排序?<form>  What color do you prefer?<br>  <input type="radio" name="colors" id="red">Red<br>  <input type="radio" name="colors" id="blue">Blue</form><script>  if (document.getElementById("red").checked == true) {    alert('working');  }</script>
查看完整描述

3 回答

?
慕田峪7331174

TA貢獻1828條經驗 獲得超13個贊

你需要一個事件監聽器


document.getElementById("red").addEventListener("change", myAlert); 


function myAlert() {

    alert('working');

}

<form>

    What color do you prefer?<br>

    <input type="radio" name="colors" id="red">Red<br>

    <input type="radio" name="colors" id="blue">Blue

</form>


查看完整回答
反對 回復 2023-07-20
?
繁星點點滴滴

TA貢獻1803條經驗 獲得超3個贊

  1. 您需要事件偵聽器 - 不建議使用內聯事件處理程序

  2. 您需要決定要測試什么

這里有兩種跑步方式

它們是收音機,所以我們不需要測試它們是否被檢查

window.addEventListener("load",function() { // when the page loads


  // testing clicking the RED only

  document.getElementById("red").addEventListener("click",function() {

    console.log("The specific Red event listener was invoked");

  });    


  // delegation

  document.querySelector("form").addEventListener("click",function(e) {

    const tgt = e.target;

    if (tgt.id==="red") console.log("Clicking in the form, we clicked the thing with ID red")

  })

});

<form>

  What color do you prefer?<br>

  <label><input type="radio" name="colors" id="red">Red</label><br>

  <label><input type="radio" name="colors" id="blue">Blue</label>

</form>


查看完整回答
反對 回復 2023-07-20
?
繁花不似錦

TA貢獻1851條經驗 獲得超4個贊

嘗試這樣:


<form>

  What color do you prefer?<br>

  <input type="radio" name="colors" id="red"/>Red<br>

  <input type="radio" name="colors" id="blue"/>Blue

</form>

<script>

document.getElementById("red").onchange = function() {

   alert('working');

}

</script>

單擊單選按鈕時需要一個事件處理程序來運行該特定代碼。



查看完整回答
反對 回復 2023-07-20
  • 3 回答
  • 0 關注
  • 177 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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