0

我试图限制一个只能点击 5 次的按钮来添加单选按钮。添加单选按钮 5 次后,它将被禁用。这件事的javascript代码是什么?点击后我只能禁用它一次。下面是代码

html

<input type ='button' id="id" onClick="a();">
        <div id='a'></div>

javascript

function a(){
    document.getElementById('a').innerHTML += "<input type='radio'>";
    document.getElementById("id").disabled=true;
}
4

5 回答 5

5

放置一个全局计数器并使用它

var counter=0;

function a(){
if(counter<5){
    document.getElementById('a').innerHTML += "<input type='radio'>";
    counter++;
}
else{
    document.getElementById("id").disabled=true;
}
}
于 2013-11-07T16:44:08.590 回答
1

单击次数的全局变量将起作用:

var clicked = 0;
function a(){
    document.getElementById('a').innerHTML += "<input type='radio'>";
    clicked++; //increment

    if (clicked == 5)
        document.getElementById("id").disabled=true;
}
于 2013-11-07T16:44:23.823 回答
0

试试这个:

var counter = 1;

function a(){
    if(counter >= 5) {
        document.getElementById("id").disabled=true;
        return false;
    }
    document.getElementById('a').innerHTML += "<input type='radio'>";

    counter++
}
于 2013-11-07T16:44:50.010 回答
0

这就是你需要的:

var counter = 0;

function a ()
{
    if (counter++ < 5)
        document.getElementById('a').innerHTML += "<input type='radio'>";
    else
        document.getElementById('id').disabled = true;
}
于 2013-11-07T16:47:21.090 回答
0

您可以计算单选按钮

<!doctype html>
<html lang="en">
<head>
<meta charset= "utf-8">
<title>Add 5</title>
<style>
input[disabled]{text-decoration:line-through;color:white;}    
</style>
<script>

function add5(){
    var radio, 
    btn= document.getElementById('add_radio'),
    pa= document.getElementById('radioDiv'), 
    R= pa.querySelectorAll('[type=radio]');

    if(R.length<5){
        radio= document.createElement('input');
        radio.type='radio'; 
        pa.appendChild(radio);
    }
    else btn.disabled= 'disabled';
}
</script>

</head>
<body>    
<p>
<input type ='button' id="add_radio" value="Add Radio"onClick="add5();">
</p>
<div id='radioDiv'></div>
</p>
</body>
</html>
于 2013-11-07T16:51:40.617 回答