当前位置: 移动技术网 > IT编程>开发语言>JavaScript > JS创建Tag标签的方法详解

JS创建Tag标签的方法详解

2017年12月12日  | 移动技术网IT编程  | 我要评论

本文实例讲述了js创建tag标签的方法。分享给大家供大家参考,具体如下:

一 . 创建标签其原理就是

创建一个节点;

var x = document.createelement("tagname")

赋予节点样式;

x.setattribute("class",类名)

对节点进行赋值;

x.innerhtml = 内容 //赋值

添加节点到父元素

要添加到的元素.appendchild(x);

二. 样式图:

三. 主要代码流程:

html部分:

<div class="container">
    <h3 style="text-align: center">单击下面得"添加"按钮添加标签</h3>
    <div class="dispanel" id="box"></div>
    <button class="btn" id="btn1">全部清除</button>
    <ul id="ul">
      <li><span>john doe1</span> <button class="clibtn btn">添加</button></li>
      <li><span>john doe2</span> <button class="clibtn btn">添加</button></li>
      <li><span>john doe3</span> <button class="clibtn btn">添加</button></li>
      <li><span>john doe4</span> <button class="clibtn btn">添加</button></li>
      <li><span>john doe5</span> <button class="clibtn btn">添加</button></li>
      <li><span>john doe6 </span><button class="clibtn btn">添加</button></li>
    </ul>
</div>

css部分:

body{
  margin:0 ;
  padding:0;
  background-color:#002f4f;
  color: #ffffff;
  font-family: "微软雅黑";
  font-size: 1em;
}
ul,h3{margin: 0;
  list-style: none;
padding: 0px}
.container{
  width:300px;
  height:350px;
  margin: 50px auto;
}
.dispanel{
  width: 290px;
  height:50px;
  background-color: #ffffff;
  margin: 0 auto;
}
.btn{
  width:100px;
  height:20px;
  color: #ffffff;
  background-color:red;
  border: 0px;
  font-size: 1em;
  margin:10px 0 10px 5px;
}
.container ul li{
  width:300px;
  height:30px;
  margin-top:10px;
}
.spanstyle{display: inline-block;
  color:#000;
  width:85px;height:22px;
  background-color: bisque;
  margin-left:5px;
  font-size: 12px;
  text-align: center;
  line-height: 22px;
}

js部分:

var oul = document.getelementbyid("ul");
var obtn = oul.getelementsbyclassname("btn");
var oli = document.getelementsbyclassname("li");
var obox = document.getelementbyid("box");
for(var i = 0;i<obtn.length;i++) {
    obtn[i].onclick = function () {
      var oa = document.createelement("span");  //创建一个节点node
      var onew = oa.setattribute("class", "spanstyle"); //将节点上增加class样式
      var ospan = this.previouselementsibling.innerhtml + " x"; //this == obtn[i] / previouselementsiling:上一个元素的兄弟节点 即 <span>
      oa.innerhtml = ospan; //将ospa的值付给新创建的节点node oa.
      obox.appendchild(oa); //将oa 添加为obox的儿子
      oa.onclick=function () {
        obox.removechild(oa); //移除这个元素
      }
    }
}
var obtn1 = document.getelementbyid("btn1");
obtn1.onclick=function () {
    obox.innerhtml=""; //清除内容
}

更多关于javascript相关内容可查看本站专题:《javascript页面元素操作技巧总结》、《javascript面向对象入门教程》、《javascript切换特效与技巧总结》、《javascript查找算法技巧总结》、《javascript错误与调试技巧总结》、《javascript数据结构与算法技巧总结》、《javascript遍历算法与技巧总结》及《javascript数学运算用法总结

希望本文所述对大家javascript程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网