如何在 jQuery 中创建 div 元素?

jqueryweb developmentfront end technology更新于 2026/2/10 10:07:17

使用 jQuery 添加 div 的方法有很多,但根据要求,点击任意方块时都必须添加一个 div。以下代码将帮助您在点击时添加 div。

Click on any square below to see the result
 <div id='box'>    
       <div class = "div" style = "background-color:blue;"></div>
       <div class = "div" style = "background-color:green;"></div>
       <div class = "div" style = "background-color:red;"></div>
</div>
$(".div").on("click",function(){
$('#box').append(
  $('<div/>')
    .attr("id", "newDiv1")
    .addClass("div")
    .append("<span/>")
      .text("hello world")
    );
});

相关文章