猿问

如何仅在选中单选按钮时触发 onlick() 函数?

我正在练习 JS,正在制作战舰游戏。我有一个 10x10 的按钮网格。每个按钮都有对应于网格上相关位置的reply_click()功能。id


<button id="00" onclick="reply_click(this.id)"></button>


function reply_click(clicked_id) {

   //some code 

}

reply_click()我只想在选中单选按钮时触发功能,并在所有其他情况下忽略它。


我尝试制作一个具有onclick()检查该单选按钮是否已选中的功能的单选按钮,但我无法reply_click()在其中放置功能。


例子:


<input type="radio" id="1s" name="ship" onclick="check()">

<label for="1s">1 square ship</label><br>


function check() {

   if (document.getElementById('1s').checked) {

       //dont know what to put here

   }

}


慕的地10843
浏览 78回答 3
3回答

三国纷争

看看这个解决方案。不太确定你在问什么,但这似乎可能有帮助。function reply_click(clicked_id)&nbsp;&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp;console.log(clicked_id);&nbsp; &nbsp; &nbsp; &nbsp;if(clicked_id !== "00")console.log('do stuff');&nbsp; &nbsp; }function check(event){&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; if(document.getElementById(event.id).checked)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;reply_click(event.id);&nbsp; &nbsp; &nbsp; &nbsp; }}<button id="00" onclick="reply_click(this.id)"></button><input type="radio" id="1s" name="ship" onclick="check(this)"><label for="1s">1 square ship</label><br>

米脂

仅当选中按钮时,您才可以使用disable该按钮enableradiofunction reply_click(clicked_id) {&nbsp; console.log("Definaley i am not disabled now: "+clicked_id);&nbsp;}function check(){&nbsp; &nbsp; if(document.getElementById('1s').checked)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;document.getElementById("00").disabled = false;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;document.getElementById("00").innerText = "Now i am enable";&nbsp; &nbsp; &nbsp; &nbsp; }}<input type="radio" id="1s" name="ship" onclick="check()"><label for="1s">1 square ship</label><br><button id="00"&nbsp; onclick="reply_click(this.id)" disabled>I am disabled</button>

月关宝盒

在reply_click中添加if语句..例如:function reply_click(clicked_id) {&nbsp; &nbsp; if (document.getElementById('1s').checked) {&nbsp; &nbsp; &nbsp; &nbsp; //&nbsp; Do stuff&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Html5
我要回答