Javascript - 尝试创建一个网格,但只能获取行.我不确定下一步该怎么做



所以我正在尝试创建一个蚀刻草图,我需要根据用户输入生成多个div(即小方块)。因此,例如,选项是您希望网格大小从 1 到 50 多少像素,并且根据答案(例如 30),我需要制作一个每边有这么多正方形的网格。问题是我只能在顶部获得那么多正方形作为一行而不是网格。链接的是我的代码,还显示了我的 JavaScript 代码,这是给我带来问题的代码。HTML/CSS大多只是样式,但它们显示在链接中。我不确定我做错了什么,因为我正在使用别人的代码作为参考,它似乎对他们有用,但对我不起作用。

https://codepen.io/faar23/pen/qjZgQY

$(document).ready(function(){
/*for (var i = 0; i < 24; i ++) {
$('#workspace').append('<div class = "row"></div>');
$('.row').height(27);
};*/
/*for now i am going to leave the above code commented out but what it 
does is instantly creates 24 boxes on the workspace
and without this, the space is empty. I am commenting it out to see if the 
.height function will wor down below...doesnt seem to*/
/*the above loop generates 24 divs dynamically without having to copy paste 
in html. the .height sets the height of the divs.
the width is set in the css under myId. this was done using this tutorial 
https://www.youtube.com/watch?v=dtgx_twX-a4 + inspecting
the elements on this project https://beachfern.github.io/sketchpad/*/
$('#mainButton').mouseenter(function(){
$('#mainButton').addClass('highlight');
});
$('#mainButton').mouseleave(function(){
$('#mainButton').removeClass('highlight');
});
/*the above code makes the main start button change color when the mouse 
enters it*/
$('.buttonhide').hide();
$('#mainButton').click(function(){
$('.buttonhide').show();
});
/*the above code hides the rest of the buttons until the main button is  
clicked, then all the buttons show themselves*/
$('#mainButton').on('click', function(){
var workspaceSize = prompt("How many boxes should make up the canvas? (1 
to 50)", "24");
/*i am going to use this user's way and see if that works better for me 
https://stackoverflow.com/questions/25518243/creating-div-grid-with-
jquery-for-loop*/
if(workspaceSize > 0 && workspaceSize <= 50){
$('#workspace').empty();
for (var i = 0; i < workspaceSize; i++){
$('#workspace').append('<div class = "row"></div>');
};
for (var x = 0; x < workspaceSize; x++){
$('.row').append('<div class = "column"></div>');
};
$('.row').height(700 / workspaceSize);
$('.column').height(700 / workspaceSize);
$('.column').width(700 / workspaceSize);
}; /*very imp closing bracket. shit doesnt work without it*/
});

});

您需要嵌套两个 for 循环,以便为每一行创建列。

这可能会起作用,或者引导您朝着正确的方向前进:

for(var i = 0; i < workspaceSize; i++){
$('#workspace').append('<div class="row" id=row'+i+'></div>');
for(var j = 0; j < workspaceSize; j++){
$('#row'+i).append('<div class="column"></div>')
}
}

最新更新