There are a thousand ways to solve what you want, the following is just an example.
What we have done here is to use different Ids for all the elements involved, and we are passing the respective Ids on 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 the this
instead of ID to detect the button pressed, but the intention was only to illustrate with a basic example.
Here, 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 use the this
to grab the button clicked, dispensing your ID
We have two functions, not to look for the element by ID every time
We are using anonymous function on setTimeout
, so that we can take advantage of the objects already solved by the previous function.
Thank you for that simplified explanation!
– Márcio Sebastião