怎么用JQuery动态添加div 比如 添加 点击一次添加按钮 增加一个div

怎么用JQuery动态添加div 比如 添加 点击一次添加按钮 增加一个div,第1张

JQuery中点击一次添加按钮,增加一个div的思路如下

给按钮注册一个点击的监听事件

在监听器中创建一个div元素附加在一个html元素后面

示例代码如下

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<style type="text/css">

#father

{

 width:150px

 height:150px

 background-color:red

}

#father div

{

 width:50px

 height:50px

 background-color:green

 font-size:12px

}

</style>

<script type="text/javascript" src="/jQuery/jquery-1.8.3.js"></script>

<script type="text/javascript">

$(document).ready(function(){

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

  

  })

  //father元素后面增加一个div元素

 $("#father").prepend("<div>新的div</div>")

})

</script>

</head>

<body>

<input type="button" value="增加div" id="btn">

<div id="father"></div>

</body>

</html>

<button id="add">添加</button>

<div id="box"></div>

<script>

$(function(){

   $("#add").on("click",function(){

      $("#box").append("<div><span>"+($("#box div").size()+1)+"</span><button>删除</button></div>")

   })

   $("#box").on("click","div button",function(){

      $(this).parent().remove()

      $("#box div span").each(function(i,e){

         $(e).text(i+1)

      })

   })

})

</script>


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/bake/11824552.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-19
下一篇2023-05-19

发表评论

登录后才能评论

评论列表(0条)

    保存