Js generates a dynamic table and adds a click event Method for each cell

Source: Internet
Author: User

Html:
Copy codeThe Code is as follows:
<Html>
<Head>
<Title> Demo </title>
</Head>
<Body>
<Label style = "font-size: 20px; width: 600px;"> dynamic table: </label> <br/>
<Table border = "1">
<Tbody id = "table">
</Table>
</Body>
</Html>

Script:
Copy codeThe 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.
}
<! -- TrLineNumber indicates the number of rows in a dynamic table, tdData indicates the number of cells in each row in a dynamic table, and the data type is array. -->
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.