如何有一定数量的列与jQuery?

时间:2019-06-26 01:35:10

标签: javascript jquery

jquery的一些新知识,我发现了这个小提琴,我可以在其中编辑和添加行和列,我希望用户只能仅编辑行数并设置4列?

https://jsbin.com/dehove/1/edit?html,css,js,console,output

HTML

<!DOCTYPE html>
<html>
    <head>
        <script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
        <meta charset="utf-8">
        <title>JS Bin</title>
    </head>
    <body>


        Set Rows:<br>
        <input type="text" id="setRows">
        <br>
        Set Columns:<br>
        <input type="text" id="setColumns">

        <button type='button'>Create Table</button>
        <p id = "demo1"></p>
        <p id = "demo2"></p>




    </body>
</html>

jQuery

    $(function(){ // DOM ready



    $("button").click(function(){

      var setRows    = +$("#setRows").val();
      var setColumns = +$("#setColumns").val();

        var table = "<table>";
        for (var i=0; i<setRows; i++){
            table += "<tr>";
            for (var j = 0; j < setColumns; j++) table += "<td>column</td>";
            table += "</tr>";
        }
        table += "</table>";


        $("p:last").after(table);

    });


});

1 个答案:

答案 0 :(得分:0)

您需要将setColumns的值更改为4

 var setColumns = 4;

也删除列的输入 您的完整HTML文件如下所示:

<!DOCTYPE html>
<html>
    <head>
        <script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
        <meta charset="utf-8">
        <title>JS Bin</title>
    </head>
    <body>


        Set Rows:<br>
        <input type="text" id="setRows">
        <br>


        <button type='button'>Create Table</button>
        <p id = "demo1"></p>
        <p id = "demo2"></p>




    </body>
</html>

这是JavaScript

    $(function(){ // DOM ready



    $("button").click(function(){

      var setRows    = +$("#setRows").val();
      var setColumns = 4;

        var table = "<table>";
        for (var i=0; i<setRows; i++){
            table += "<tr>";
            for (var j = 0; j < setColumns; j++) table += "<td>column</td>";
            table += "</tr>";
        }
        table += "</table>";


        $("p:last").after(table);

    });


});

This is the js bin 希望这会有所帮助:)