抛出问题
对一个p标签进行克隆,第一次克隆1个结果,第二次克隆出来2个结果,第三次克隆出来的4个结果,怎每次得到自己想要的结果?????????
待解决问题代码展示
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<style>
.red{
color: red;
}
</style>
<body>
<ul id="hello">
<li class="a"></li>
<li class="b"></li>
<li></li>
</ul>
<p>hello1</p>
</body>
<script type="text/javascript" src="js/jquery.js" ></script>
<script>
$("li").each(function(){
var a=$(this).is(".a");
var b=$(this).is(".b");
if(a){
var html=$("p").clone();
html.addClass("red");
$(this).append(html);
}else if(b){
$(this).append($("p").clone());
}else{
$(this).append($("p").clone());
}
})
</script>
</html>
页面输出结果
结论
每次克隆会生成双倍的p标签,因此每次克隆会产生原来p标签的两倍,得到的是一个数组。因此想要得到本次的结果,并添加样式,只需要取数组的最后一个就行了
修改后的代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<style>
.green{
color:green;
}
.red{
color: red;
}
</style>
<body>
<ul id="hello">
<li class="a"></li>
<li class="b"></li>
<li></li>
</ul>
<p>hello1</p>
</body>
<script type="text/javascript" src="js/jquery.js" ></script>
<script>
$("li").each(function(){
var a=$(this).is(".a");
var b=$(this).is(".b");
if(a){
var html=$("p").clone();
html.addClass("red");
$(this).append(html);
}else if(b){
$(this).append($("p").clone().addClass("green").last());
}else{
$(this).append($("p").clone().last());
}
})
</script>
</html>
页面展示结果