问题
I am working on a pong game in java script where one can change the difficulty level using a set of radio buttons
<form action="">
<input type="radio" name="level" value="8">Beginner<br>
<input type="radio" name="level" value="4">Intermediate<br>
<input type="radio" name="level" value="2">Pro<br>
</form>
The level adjusts well on the first try but when someone clicks on another radio button the game court is affected and keeps on refreshing. I am using html 5 and set the fps to 60. What I wanted is after a new page refresh, when one selects one radio button, the remaining buttons should become disabled till the user refreshes the page. Is there a way to do this in vanilla js?
回答1:
You can loop over radio buttons collection and change their disabled status on change event. For example like this:
var radios = [].slice.call(document.querySelectorAll('input[name=level]'));
radios.forEach(function(radio) {
radio.addEventListener('change', function() {
radios.forEach(function(r) {
r.disabled = r !== radio;
});
});
});
<form action="">
<input type="radio" name="level" value="8">Beginner<br>
<input type="radio" name="level" value="4">Intermediate<br>
<input type="radio" name="level" value="2">Pro<br>
</form>
回答2:
If you just want to disable them after one click then this should do..
<form action="" name="formName">
<input type="radio" name="level" value="8">Beginner<br>
<input type="radio" name="level" value="4">Intermediate<br>
<input type="radio" name="level" value="2">Pro<br>
</form>
Onclick event
$("input:radio[name=level]").click(function(){
var radios = document.formName.level;
for (var i=0, iLen=radios.length; i<iLen; i++) {
radios[i].disabled = true;
}
});
Here is a fiddle Click here
回答3:
You can do it with plain javascript.
var buttons = document.getElementsByName('level');
for(var i = 0; i < buttons.length; i++)
{
buttons[i].onclick = function()
{
for(var j = 0; j < buttons.length; j++)
{
if(j != i)
{
buttons[j].setAttribute('disabled', 'true');
}
}
}
}
Also I would get rid of the <form>
tag since it serves no purpose here.
来源:https://stackoverflow.com/questions/33287230/after-selecting-one-radio-button-i-want-the-remaining-buttons-to-become-disable