Use js to dynamically create tags and set attributes.
When writing jsp pages, we often encounter this situation: the number of data retrieved from the backend is uncertain, so we are not sure how to design it when writing jsp pages on the front end. In this case, you need to dynamically create tags using js:
1. Create a tag: Create a div in the body as follows;
<Script> function fun () {var frameDiv = document. createElement ("div"); // create a label var bodyFa = document. getElementById ("bodyid"); // obtain the parent class (that is, the node at the upper level) bodyFa of the frameDiv through the ID. appendChild (frameDiv); // Add the created node frameDiv to the parent class body;} <script> <body id = "bodyid"> <! -- Add the div tag here --> </body>
2. Add attributes: add the corresponding attributes to the created Tag:
FrameDiv. setAttribute ("id", "divid"); // set the id value for the created div; frameDiv. className = "divclass"; // set the class for the created div; // Add the displayed value to a label; var h = document. createElement ("h1"); h. innerHTML = data [I]. name; var p = document. createElement ("p"); p. innerHTML = "value to be displayed ";
3. Create a tag add event:
A. Without parameters:
FrameDiv. onmousedown = fun; // ps: The function name fun cannot be followed by parentheses; otherwise, the function will be executed when the tag is created, rather than when the mouse is pressed;
B. There are parameters:
frameDiv.onmousedown = function(){ fun(this); }
C. The function to be called;
Function fun () {alert ("press the mouse ");}
4. If you are worried that the created tag is not overwritten, you can replace it:
Var divFlag = document. getElementById ("divFlag"); var divMain = document. createElement ("div"); if (divFlag! = Null) {body. replaceChild (divMain, divFlag); // replace the original one} divMain. setAttribute ("id", "divFlag ");
The above article uses js to dynamically create tags and set the attribute method to share all the content with you. I hope to give you a reference, and I hope you can provide more support for the customer's house.