+ 1
How can I make an individual counter for each button?
I’m trying to make buttons that use the same function to display changing text. I can make one button work, but to get a second button functioning individually it needs its own counter. How can I accomplish this? https://code.sololearn.com/W8lHK8Oz5JaL/?ref=app
2 ответов
+ 2
Use an array of counter, each array element represents a counter for a particular button.
var counter = [0,0,0,0];
function countertest(buttonId, text1, text2, text3, text4)
{
counter[buttonId]++;
var el = document.getElementById("btn" + buttonId);
switch(counter[buttonId])
{
case 1:
el.innerHTML = text1;
break;
case 2:
el.innerHTML = text2;
break;
case 3:
el.innerHTML = text3;
break;
default:
el.innerHTML = text4;
counter[buttonId] = 0;
}
}
In this example a maximum of 4 buttons are supported, to call the function pass the button number instead of its Id, the function will refer to the specific button internally.
<button id = "btn1" onclick = "countertest(1, 'option 1a', 'option 1b', 'option 1c', 'option 1d')">click here</button>
+ 1
that worked perfectly, thanks