var show=[
"p1",
"p2",
"p3"
];
var n;
function show(n){
for(n=1;n<=3;++n){
document.getElementById("show").innerHTML=show[n];
}
}
<button onclick="show(1)">b1</button>
<button onclick="show(2)">b2</button>
<button onclick="show(3)">b3</button>
<p id="show"></p>
I am trying to print p1,p2,p3 when I click b1,b2,b3 respectively. How can I do it.
asked Apr 13, 2020 at 10:46
user12054439
-
Rename the array, it overrides the function with the same name. Also, arrays have zero-based indexing.Teemu– Teemu2020年04月13日 10:49:21 +00:00Commented Apr 13, 2020 at 10:49
2 Answers 2
Your code has several problems.
First, do not name your variable and the function with the same name. In this example, you can rename the array as showArr.
Then you need to remove for loop (it is against what you are trying to achieve). And you need to pass index - 1 when getting the array item with index.
And there is no need for a variable n in the global scope (it is redundant).
var showArr = [
"p1",
"p2",
"p3"
];
function show(n) {
document.getElementById("show").innerHTML = showArr[n - 1];
}
<button onclick="show(1)">b1</button>
<button onclick="show(2)">b2</button>
<button onclick="show(3)">b3</button>
<p id="show"></p>
answered Apr 13, 2020 at 10:50
Harun Yilmaz
8,5893 gold badges30 silver badges41 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Just don't use the same name show for the variable and the function:
var show = [
"p1",
"p2",
"p3"
];
function showIt(n) {
document.getElementById("show").innerHTML = show[n - 1];
}
<button onclick="showIt(1)">b1</button>
<button onclick="showIt(2)">b2</button>
<button onclick="showIt(3)">b3</button>
<p id="show"></p>
answered Apr 13, 2020 at 10:50
uminder
26.4k6 gold badges45 silver badges91 bronze badges
Comments
default