When we write jsp pages, we often encounter this situation: the number of data obtained from the background is uncertain. At this time, when writing jsp pages on the front end, we are not sure how to design it. At this time, you need to dynamically create tags through js:
1. Create a certain tag: Create an instance of p in the body as follows;
<script> function fun(){ var framep = document.createElement("p");//创建一个标签 var bodyFa = document.getElementById("bodyid");//通过id号获取framep 的父类(也就是上一级的节点) bodyFa .appendChild(framep);//把创建的节点framep 添加到父类body 中; } <script> <body id="bodyid" > <!--在此添加p标签--> </body>
2. Add attributes: Add attributes to the created tag Corresponding attributes:
framep .setAttribute("id", "pid");//给创建的p设置id值; framep .className="pclass"; //给创建的p设置class; //给某个标签添加显示的值; var h = document.createElement("h1"); h.innerHTML = data[i].name; var p = document.createElement("p"); p.innerHTML = "要显示的值";
3. Created tag addition event:
a. Without parameters:
framep.onmousedown = fun;//ps:函数名fun后面一定不能带括号,否则会在创建标签的时候执行函数, 而不是鼠标按下时执行;
b. With parameters:
framep.onmousedown = function(){ fun(this); }
c. The function to be called;
function fun(){ alert("鼠标按下"); }
4. If you are worried that the created tag will not be overwritten, you can replace it:
var pFlag = document.getElementById("pFlag"); var pMain = document.createElement("p"); if(pFlag != null){ body.replaceChild(pMain, pFlag);//把原来的替换掉 } pMain.setAttribute("id", "pFlag");
Related recommendations:
JS dynamically create tag code example
PHP Create tag cloud function code_PHP tutorial
js dynamically create tag example code_javascript skills
The above is the detailed content of How to dynamically create tags and set attributes in js. For more information, please follow other related articles on the PHP Chinese website!