所以我试图创建一个蚀刻草图,我需要根据用户输入生成多个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*/
});
});
答案 0 :(得分:0)
您需要嵌套两个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>')
}
}