jQuery实现元素的插入

 效果图:

jQuery实现元素的插入

图(1) 初始效果

jQuery实现元素的插入

图(2) 点击' 插入到此元素前面 '效果

 代码如下:

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <script src="https://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 type="number" min="0" max="4" value="4" /> <button>插入到此元素前面</button> <button>插入到此元素后面</button> <div> </div> </body> <script type="text/javascript"> $(function(){ var mainDiv=$("#main"); for(var i=1;i<6;i++){ var $divs=$("<div>我是第"+i+"个</div>") mainDiv.append($divs) } var newDiv=$("<div>我是新的</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>

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持脚本之家!

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwzdpz.html