There are a thousand ways to solve what you want, this is just an example.
What we did here was to use different IDs for all elements involved, and we are passing the respective IDs in each onClick
:
<script language="JavaScript">
function conta(b,s) {
botao = document.getElementById(b);
contador = document.getElementById(s);
botao.disabled=true;
if(contador.innerHTML==0) {
botao.disabled=false;
contador.innerHTML = 10;
return false;
}
contador.innerHTML = contador.innerHTML - 1;
setTimeout('conta("'+b+'","'+s+'")', 1000);
}
</script>
<input type="button" id="b1" value="botao1" onclick="conta('b1','s1')" class="btn">
<span id="s1">10</span>
<br/><br/>
<input type="button" id="b2" value="botao2" onclick="conta('b2','s2')" class="btn">
<span id="s2">10</span>
There are ways to optimize much more, for example, by calling a function and using a second function as a counter, and even using this
instead of ID to detect the button pressed, but the intention was only illustrate with a basic example.
Here is a different version, to show some things:
<script language="JavaScript">
function dispara( span ) {
conta( this, document.getElementById( span ) );
}
function conta( botao, contador ) {
botao.disabled=true;
if(contador.innerHTML==0) {
contador.innerHTML = 10;
botao.disabled=false;
return false;
}
contador.innerHTML = contador.innerHTML - 1;
setTimeout( function(){conta( botao, contador )}, 1000 );
}
</script>
<input type="button" value="botao1" onclick="dispara('s1')" class="btn">
<span id="s1">10</span>
<br/><br/>
<input type="button" value="botao2" onclick="dispara('s2')" class="btn">
<span id="s2">10</span>
-
We used this
to get the button clicked, dispensing its id
-
We have two functions, so we do not get the element by ID every time
-
We are using anonymous function in setTimeout
, so we can take advantage of objects already resolved by the previous function.