我们假设您有以下表单,用户输入两个数字:
<form>
<input type="text" id="x">
<input type="text" id="y">
</form>
然后你可以使用jQuery生成网格如下:
var x = parseInt($('#x').val(), 10),
y = parseInt($('#y').val(), 10);
grid(x, y);
function grid(x, y) {
var i = -1,
j = -1,
step = 5, //assuming that each grid unit = 5
$grid = $('<div>', {'id':'grid'}),
$square = $('<div>', {'class':'square'}),
$label,
w = parseInt($square.css('width'), 10) + 2; //the width of each square + 2 pixels for the borders;
$grid.width(w * x);
while(++i < x) {
while(++j < y) {
if(j === 0) {
$label = $('<span>', {'class':'label'});
$label.css('top', j * w).css('left', i * w).html(i * step);
}
if(i === 0 && j > 0) {
$label = $('<span>', {'class':'label'});
$label.css('top', j * w).css('left', i * w).html(j * step);
}
$grid.append($square.clone(), $label);
}
j = -1;
}
$('body').append($grid);
}
CSS:
#grid { overflow: hidden; border-left: 1px solid #000; border-top: 1px solid #000; position: relative; }
div.square { width: 50px; height: 50px; float: left; border-bottom: 1px dotted #000; border-right: 1px dotted #000; }
span.label { position: absolute; background: #fff; font-weight: bold; z-index: 10; }
比方说,这里是我们覆盖(对话框):
<div>
<input type="text" id="x">
<input type="text" id="y">
<button id="build-grid" type="button">Build grid</button>
</div>
然后,您将一个onclick事件附加到build-gr ID按钮。所以,当按钮被点击时,我们读取x和y值并构建网格。
$('#build-grid').on('click', function(e){
e.preventDefault();
var x = parseInt($('#x').val(), 10), //get our values from the input fields
y = parseInt($('#y').val(), 10);
grid(x, y); // build the grid
});
WOW!谢谢。 @Petemk。我迫不及待想要尝试一下。你是个天才。 :-) Rachel – user1204493
@petemk好的。我尝试过,但它不适合我。我确定这是因为我对jQuery不是很熟悉。对于一切都很新,但是如何让网格显示出来?我需要将网格ID应用到另一个页面吗?我尝试过使用画布,也是一个内容区域,但是当我在表单中键入两个数字并在最后一个数字后面输入时,什么都不会发生。你会带我穿过它 - 就像一个婴儿。对不起。 --Rachel – user1204493
好的,首先,你想让两个输入字段与网格在同一页面上吗? – petermk