使用javascript / jquery创建动态div

时间:2014-05-07 01:40:01

标签: javascript jquery html css html5

我想使用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>

我想在&#34;包装器&#34;之间添加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");
                    }
            }
        }
    });    
});

1 个答案:

答案 0 :(得分:1)

我在这里更新了fiddle以帮助您入门。

创建动态div的方法是首先执行以下操作 获取容器的句柄。在这种情况下,它将是$(".wrapper")

我不知道您希望如何完成网格,但我已经将每行视为一个div(带有'n'行),每行包含'n'列div。

要创建div,您可以使用方便的$('<div>', {...})表示法。当你经历循环时,不要忘记附加到容器。

将演示文稿保存在CSS中(您可以看到它已经在小提琴中完成)。

此处已复制代码供您参考。

$(".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);
    }
}
相关问题