我试图限制一个只能点击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;
}
答案 0 :(得分:5)
放置一个全局计数器并使用它
var counter=0;
function a(){
if(counter<5){
document.getElementById('a').innerHTML += "<input type='radio'>";
counter++;
}
else{
document.getElementById("id").disabled=true;
}
}
答案 1 :(得分:1)
点击次数的全局变量将起作用:
var clicked = 0;
function a(){
document.getElementById('a').innerHTML += "<input type='radio'>";
clicked++; //increment
if (clicked == 5)
document.getElementById("id").disabled=true;
}
答案 2 :(得分:0)
试试这个:
var counter = 1;
function a(){
if(counter >= 5) {
document.getElementById("id").disabled=true;
return false;
}
document.getElementById('a').innerHTML += "<input type='radio'>";
counter++
}
答案 3 :(得分:0)
这就是你需要的:
var counter = 0;
function a ()
{
if (counter++ < 5)
document.getElementById('a').innerHTML += "<input type='radio'>";
else
document.getElementById('id').disabled = true;
}
答案 4 :(得分: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>