Hi,
I am just starting to work with functions in Javascript. I can’t figure out why the following function rand() will not return a random number when called. The random number is used to set the background of the table cells.
<!DOCTYPE html>
<html lang="en">
<head>
<title>
Generate table
</title>
</head>
<body>
<input type="button" value="Generate table" onclick="generate_table()">
<script language="javascript">
function generate_table(){
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
for(var i = 0; i < 20; i++){
var row = document.createElement("tr");
for(var j = 0; j < 20; j++);
var cell = document.createElement("td");
function rand(){
var r = Math.floor(Math.random()*255);
return r;
}
cell.style.background = "rgb(" + rand() + "," + rand() + "," + rand()")";
cell.style.width = "50px";
cell.style.height = "50px";
cell.setAttribute("align", "center");
var cellText = document.createTextNode(" ");
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
}
</script>
</body>
</html>
Thanks,
Shane