(x)
。(x)
在表格中创建(x)
行和x
列。我知道javascript里面和外面......就数学而言。只需指出正确的方向,即在DOM中同时在每个TR
内创建3 TD
和3 TR
。
我已经尝试了.clone
,但我一直在失败......感谢任何帮助!
ORIGINAL JS:
function create(x){
var board = [];
for(var i=0;i<x;i++){
var tempArr = [];
for(var j=0;j<x;j++){ tempArr[j] = ""; }
board.push(tempArr);
}
return board;
}
create(3);
完整HTML:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Tic Tac Toe! (and more...)</title>
<meta name="description" content="Tic Tac Toe">
<meta name="author" content="SinSysOnline">
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<style>
body{
font-family:"Lucida Console", Monaco, monospace;
}
td{
border-right:1px solid #000;
border-bottom:1px solid #000;
width:100px;
height:100px;
text-align:center;
font-size:72px;
}
td:last-child{
border-right:none;
border-bottom:1px solid #000;
}
tr:last-child td{
border-bottom:none;
}
</style>
</head>
<body>
<div id="dashboard">
<input type="text" value="How large is your grid? (default 3)" size="35" />
</div>
<table id="board">
<tr></tr>
</table>
<script>
(function($) {
var $board = $('#board');
var td = "<td></td>", $tr = $("<tr></tr>");
function create(x) {
$board.empty();
var arr = [];
for(var i = 0; i < x; i++) {
arr.push(td);
}
var $trCloned = $tr.clone().append(arr.join(''));
for(var j = 0; j < x; j++) {
$board.append($trCloned);
}
}
function compChoice(x){
var a = Math.floor(Math.random(10)*x),
b = Math.floor(Math.random(10)*x);
while(board[a][b]!==""){
a = Math.floor(Math.random(10)*x);
b = Math.floor(Math.random(10)*x);
}
board[a][b]="X";
}
function userChoice(a,b){
var select = [a,b];
if(board[a][b]!==""){
alert("That's not a valid move... try again");
} else {
board[a][b]="O";
}
}
var x = prompt("How large would you like your grid? (3-10)");
var board = create(x);
})(jQuery);
</script>
</body>
</html>
完全JS:
(function($) {
var $board = $('#board');
var td = "<td></td>", $tr = $("<tr></tr>");
function create(x) {
$board.empty();
var arr = [];
for(var i = 0; i < x; i++) {
arr.push(td);
}
var $trCloned = $tr.clone().append(arr.join(''));
for(var j = 0; j < x; j++) {
$board.append($trCloned);
}
}
function compChoice(x){
var a = Math.floor(Math.random(10)*x),
b = Math.floor(Math.random(10)*x);
while(board[a][b]!==""){
a = Math.floor(Math.random(10)*x);
b = Math.floor(Math.random(10)*x);
}
board[a][b]="X";
}
function userChoice(a,b){
var select = [a,b];
if(board[a][b]!==""){
alert("That's not a valid move... try again");
} else {
board[a][b]="O";
}
}
var x = prompt("How large would you like your grid? (3-10)");
var board = create(x);
})(jQuery);
答案 0 :(得分:1)
使用嵌套循环会容易得多。 例如:http://jsfiddle.net/7qmdY/
$("#go").click(function(){
var size = $("#size").attr("value");//get size value;
for(var i=0;i < size;i++){// first loop to create row
$("#board").append("<tr>");
for(var j=0;j < size;j++){// nested loop to create column in all rows
$("#board").append("<td>1</td>");
}
$("#board").append("</tr>");
}
});