我想使用 javascript 或 jquery 创建动态 div,但不知道该怎么做。
<div id="clickable">
<button class="start">Default</button>
<button class="random">Randon</button>
<button class="gradient">Gradient</button>
<button class="trail">Trail</button>
<button class="clear">Clear</button>
<div id="start">Please click on one of the buttons to get started!</div>
</div>
<div class="wrapper">
</div>
我想在“包装器”类之间添加 x*x div。例如,当有人键入 4 时,输出将是一个 4x4 的 div 网格。先感谢您!
目前我有这个,但没有任何反应。
$(".start").click(function() {
total = prompt("Please enter a number");
});
$(document).ready(function() {
$(".start").click(function() {
function begin(total) {
for (var i = 0; i < total; i++) {
var rows = document.createElement("div");
for (var i = 1; i < rows; i++) {
var columns = document.createElement("div");
}
}
}
});
});
最佳答案
我已经更新了一个fiddle在这里帮助您入门。
创建动态div的方法是首先执行以下操作
获取容器的句柄。在这种情况下,它将是 $(".wrapper")
我不知道您希望如何完成网格,但我已经通过将每一行视为一个 div(具有“n”行)并且每行包含“n”列 div 来实现。
要创建一个 div,您可以使用方便的 $('<div>', {...})
符号。在执行循环时,不要忘记附加到容器。
保留 CSS 中的演示文稿(您可以看到它也已在 fiddle 中完成)。
代码已经复制在这里供大家引用。
$(".start").click(function () {
total = prompt("Please enter a number");
console.log("Total is", total);
//Now call the grid creator.
createGrid(total);
});
function createGrid(total) {
//Get the wrapper handle.
var $container = $(".wrapper");
//Loop through each row.
for (var rowIndex = 0; rowIndex < total; rowIndex++) {
//Create the skeleton for the row.
var rowId = "row-" + rowIndex; //Not needed.
var $row = $("<div>", {
"class": "row",
"id": rowId
});
//Loop through each column
for (var columnIndex = 0; columnIndex < total; columnIndex++) {
//Create skeleton for the column. (Note: IDs have to be unique)
var columnId = rowIndex + "-col-" + columnIndex; //Not needed.
var $column = $("<div>", {
"class": "column",
"id": columnId
});
//Append to the row div.
$row.append($column);
}
//Finally append this row to the container.
$container.append($row);
}
}
关于javascript - 使用 javascript/jquery 创建动态 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23507285/