HTML5用JavaScript克隆标签

html-css012

HTML5用JavaScript克隆标签,第1张

<!DOCTYPE html>

<html>

  <head>

<meta http-equiv="Content-Type" content="text/html charset=UTF-8">

<title>

RunJS 演示代码

</title>

<style>

.content{

background-color:black

width:50px

height:50px

border-radius:90px

line-height:50px

color:white

text-align:center

cursor:pointer

float:left

-webkit-user-select:none

-moz-user-select:none

-ms-user-select:none

user-select:none

}

</style>

<script>

onload=function(){

document.body.onclick=function(e){

e = e || window.event

var ta = e.target || e.srcElement || e.toElement

if(ta.id == "c"){

this.appendChild(ta.cloneNode(true))

}

}

}

</script>

  </head>

<body>

    <div class='content' id="c">

点我

</div>

  </body>

</html>

给select加个样式,改变它的效果就好了

<style>

select{

width:300px

border:#CCC solid 1px

border-radius:2px

font-size:18px

color:#CCC

line-height:35px

height:35px

}

</style>

<body>

<select>

<option>select Box

</option>

</select>

</body>

clone() 方法生成被选元素的副本,包含子节点、文本和属性。

html() 方法方法返回或设置被选元素的内容 (innerHTML)。如果该方法未设置参数,则返回被选元素的当前内容。

两者的区别就是 html() 只能得到这个节点的 innerHTML;而 clone() 除了能得到这个节点的 innerHTML,这个节点本身的文本、属性也是能得到的,如果指定了参数 true,那么连这个节点绑定的事件也会克隆一遍。

例如:

<div id="A">

    <div id="B">

    </div>

</div>

<script>

    $("#A").click(function() {

        alert("Ohh~")

    })

</script>

那么:

$("#A").html() 只能得到 <div id="B"></div>;

$("#A").clone() 得到的是 <div id="A"><div id="B"></div></div>;

$("#A").clone(true) 不仅得到了 <div id="A"><div id="B"></div></div>,同时连 A 绑定的 click 事件也能一并克隆。