Home  >  Article  >  Web Front-end  >  Two ways to create createElement in javascript_javascript skills

Two ways to create createElement in javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:59:121464browse

The examples in this article describe the two creation methods of createElement in javascript. Share it with everyone for your reference. The specific implementation method is as follows:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>CreateElement的两种创建方式</title>
 <script type="text/javascript">
 function CreateButton1() {
  var btn = document.createElement("input");
  btn.type = "button";
  btn.value = "我是动态创建的1";
  btn.onclick = function () {
  alert(this.value);
  }
  document.body.appendChild(btn);
 }
 function CreateButton2() {
  var btn = document.createElement("<input type='button' value='我是动态创建的2' "+"onclick='OnClick2(this)' />");
  document.body.appendChild(btn);
 }
 function OnClick2(btn) {
  alert(btn.value);
 }
 function CreateLink() {
  var link = document.createElement("<a href='http://www.baidu.com'>百度</a>");
  //注意这里链接的文本“百度”是不会显示出来的,
  //必须设置innerText或innerHTML
  link.innerText = "百度";
  document.body.appendChild(link);
 }
 function CreateLabel() {
  var lbl = document.createElement("label");
  lbl.setAttribute("for", "userName");
  lbl.setAttribute("myAge", "12");
  //可以设置自定义标示
  lbl.innerText = "用户名:";
  document.body.appendChild(lbl);
 }
 </script>
</head>
<body>
 <input type="button" value="动态创建按钮1" onclick="CreateButton1()" />
 <input type="button" value="动态创建按钮2" onclick="CreateButton2()" />
 <input type="button" value="动态创建链接" onclick="CreateLink()" />
 <input type="button" value="动态创建Label" onclick="CreateLabel()" />
 <input type="text" id="userName" value="李莫" />
</body>
</html>

I hope this article will be helpful to everyone’s JavaScript programming design.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn