재우니의 블로그

 

https://jsfiddle.net/shimpark/6Lxf55rq/

 

<button id="btnGenerateTable">Generate Table</button>
<br>
<div id="parentHolder">
</div>



<script>
    
    var bookDetails = [];
    bookDetails.push(["Book Id", "Book Title", "Author"]);
    bookDetails.push(["1", "Mein Kampf ", "Adolf Hitler"]);
    bookDetails.push(["2", "Relativity: The Special and the General Theory", "Albert Einstein"]);
    bookDetails.push(["3", "Think and Grow Rich", "Napoleon Hill"]);
    bookDetails.push(["4", "The Art of Public Speaking", "Dale Carnegie"]);
    bookDetails.push(["5", "Tales of Secret Egypt", "Sax Rohmer"]);
    bookDetails.push(["6", "The Fakir", "BHARUCHA"]);
    bookDetails.push(["7", "Code Name God", " Mani Bhaumick"]);

    $('#parentHolder').on('click', 'td', function () {
        alert($(this).text());
        alert($(this).attr("id"));
    });

    $("#btnGenerateTable").on('click', function (e) {
        e.preventDefault();
        var parentDiv = $("#parentHolder");
        parentDiv.html("");
        var aTable = $("<table>", {
            "id": "newTable"
        }).appendTo(parentDiv);

        var rowCount = bookDetails.length;
        var colmCount = bookDetails[0].length;

        // For loop for adding header .i.e th to our table
        for (var k = 0; k < 1; k++) {
            var fragTrow = $("<tr>", {
                "class": "trClass"
            }).appendTo(aTable);

            for (var j = 0; j < colmCount; j++) {
                $("<th>", {
                    "class": "thClass"
                }).prependTo(fragTrow).html(bookDetails[k][j]);
            }
        }

        //For loop for adding data .i.e td with data to our dynamic generated table
        for (var i = 1; i < rowCount; i < i++) {
            var fragTrow = $("<tr>", {
                "class": "trClass"
            }).appendTo(aTable);

            for (var j = 0; j < colmCount; j++) {
                $("<td>", {
                    "class": "tdClass",
                    "id": "id_" + i + "_" + j
                }).appendTo(fragTrow).html(bookDetails[i][j]);
            }
        }
    });




</script>