관리 메뉴

심재운 블로그

jquery 자동 행 추가 및 이벤트 핸들러 설정 본문

프로그래밍/jQuery

jquery 자동 행 추가 및 이벤트 핸들러 설정

재우니 2017. 1. 18. 22:06


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>


Tag
0 Comments
댓글쓰기 폼