+ 3
different output in array
1) <button onclick="klik();">klik me</button> <p id="here"></p> <script> var x = 0; function klik(){ var scripts = ["PHP","HTML","JS"]; document.getElementById("here").innerHTML += scripts[x] + "<br >"; x++; }</script> 2)<button onclick="klik();">klik me</button> <p id="here"></p> <script> function klik(){ var x = 0; var scripts = ["PHP","HTML","JS"]; document.getElementById("here").innerHTML += scripts[x] + "<br >"; x++; }</script> why the output is different ?, and why no 2 just output "PHP" ?
2 Respostas
+ 10
In the second case the variable x will be always 0, because after the onclick event you declare again and again the variable x with the 0 value.
// FIXED VERSION
<button onclick="klik();">klik me</button>
<p id="here"></p>
<script>
var x = 0;
function klik( ) {
var scripts = ["PHP","HTML","JS"];
if (x >= scripts.length) x=0;
document.getElementById("here").innerHTML += scripts[ x++ ] + "<br >";
}
</script>
+ 2
Thanks for your response maz, anyway the FIXED VERSION of your code is the best 👍