Javascript to generate a dynamic table and add a click event for each cell _ javascript tips

Source: Internet
Author: User
This article describes how to use javascript to generate a dynamic table and add click events for each cell. For more information, see html:

The Code is as follows:




Demo


Dynamic table:







Script:

The Code is as follows:


Script
Function getColumnDetail (column ){
Column. style. color = "blue"; // set the clicked cell to blue
Alert (column. innerHTML); // the content in the clicked cell is displayed.
}

Function setTable (trLineNumber, tdData ){
Var _ table = document. getElementById ("table ");
Var _ row;
Var _ cell;
For (var I = 0; I <trLineNumber; I ++ ){
_ Row = document. createElement ("tr ");
Document. getElementById ("table"). appendChild (_ row );
For (var j = 0; j <tdData. length; j ++ ){
_ Cell = document. createElement ("td ");
_ Cell. onclick = function () {getColumnDetail (this)}; // Add a click event for each cell
_ Cell. innerText = tdData [j];
_ Row. appendChild (_ cell );
}

}
}
Script


Call the setTable (trLineNumber, tdData) function to dynamically generate a table and set a click event for each cell. After the event is triggered, the content of the clicked cell is displayed, and the data becomes blue.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.