这篇文章主要介绍“jQuery怎么实现元素插入”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“jQuery怎么实现元素插入”文章能帮助大家解决问题。
效果图:
图(1) 初始效果
图(2) 点击' 插入到此元素前面 '效果
代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<style type="text/css">
.div{
width: 200px;
height: 200px;
border: 1px solid #008080;
background-color: #0095FF;
text-align: center;
line-height: 200px;
color: white;
font-size: 25px;
float: left;
}
#num{
height: 30px;
text-align: center;
font-size: 16px;
}
#main{
width: 100%;
height: 400px;
margin-top: 20px;
}
button{
height: 35px;
}
.newDiv{
width: 200px;
height: 200px;
border: 1px solid #008080;
background-color: #009999;
text-align: center;
line-height: 200px;
color: white;
font-size: 25px;
float: left;
}
</style>
<body>
插入到第几个元素:<input id="num" type="number" min="0" max="4" value="4" />
<button id="insertFront">插入到此元素前面</button>
<button id="insertBack">插入到此元素后面</button>
<div id="main">
</div>
</body>
<script type="text/javascript">
$(function(){
var mainDiv=$("#main");
for(var i=1;i<6;i++){
var $divs=$("<div class='div' id='a"+i+"'>我是第"+i+"个</div>")
mainDiv.append($divs)
}
var newDiv=$("<div class='newDiv'>我是新的</div>");
var front=$("#insertFront")
var back=$("#insertBack")
front.click(function(){
var numVal=parseInt($("#num").val());
var div1=document.getElementById("a"+numVal+"");
newDiv.insertBefore(div1)
})
back.click(function(){
var numVal=parseInt($("#num").val());
var div1=document.getElementById("a"+numVal+"");
newDiv.insertAfter(div1);
})
})
</script>
</html>
关于“jQuery怎么实现元素插入”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注亿速云行业资讯频道,小编每天都会为大家更新不同的知识点。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://mp.weixin.qq.com/s/K1rMfKqpgIwG5zt1Dss2sA