I’m fiddling with javascript to get the hang of it. I am trying to built an x by x grid programatically–which I’ll eventually try to get to be minesweeper. I have a function to write a single row with x entries. I have another function that loops, calling the single row function x times. The idea is that by calling the row function x times, I’ll get an x by x grid. But in my current code, the looping function is calling the single line function 1 time and I can’t figure out why. When I use alerts to count iterations, the loop fires five times–but not when the writeOneRow function is included. I get the same behavior in IE and Chrome. Can anyone point out my (likely bonehead) error:
<html>
<body>
<script type="text/JavaScript">
function writeRows(loop) {
for (i=0;i<loop;i++){
writeOneRow(loop); //this is only called once. Why?
}
}
function writeOneRow(num) {
var b = "<Div style='float:left; border-style:solid; margin:10px'> Test </div>"
var string =""
for (i=0;i<num;i++){
string= string+ b ;
}
var line = document.createElement('div');
line.innerHTML = string ;
document.body.appendChild(line);
}
</script>
<a href="#" onclick="javascript:writeRows(5);return false;">InsertRow</a>
</body>
</html>
Your variable
iis a global. Usevarto make them local.