jquery如何在DIV的后面动态添加一个DIV?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了jquery如何在DIV的后面动态添加一个DIV?相关的知识,希望对你有一定的参考价值。

如:我想在第2个DIV的后面动态去添加一个DIV,该如何实现?
<div>
<div>1</div>
<div>2</div>
<div>3</div>

</div>

使用 after 方法可以实现这种效果。

例如,我想在第2个DIV的后面动态去添加一个DIV,该如何实现?


html 代码:

<div id="parent">
    <div id="one">1</div>
    <div id="two">2</div>
    <div id="three">3</div>
</div>


Js 代码:


$(function()
    $("#two").after("<div>我是新添加的内容</div>");
    //选择 ID 为 #two 的 DIV 节点,在其后边添加一个 DIV 节点
);


先掌握这种方法,然后再探究其他更多实现方式。

参考技术A //纯手打没测试但是实现肯定是这样的.不保证直接运行
$('div>div:eq(1)').after('<div></div'>);
参考技术B 在所有段落之后插入一些HTML标记代码。
HTML 代码:<p>I would like to say: </p>jQuery 代码:$("p").after("<b>Hello</b>");结果:<p>I would like to say: </p><b>Hello</b>

jquery的after
参考技术C   $("#btn").click(function()
  $("#test").append(" <div>XXXXXXXXXXXXX</div>");
  //或者 $("<div>XXXXXXXXXXXXX</div>").appendTo("#test");
  );
  
  $("#btn").live("click",function()
  $("#test").append(" <div>XXXXXXXXXXXXX</div>");
  //或者 $("<div>XXXXXXXXXXXXX</div>").appendTo("#test");
  );
  
  $("#btn").bind("click",function()
  $("#test").append(" <div>XXXXXXXXXXXXX</div>");
  //或者 $("<div>XXXXXXXXXXXXX</div>").appendTo("#test");
  );
参考技术D <div id="maindiv">
<div>1</div>
<div>2</div>
<div>3</div>

</div>

$("#maindiv").append("<div></div>")追问

大哥,你别害我啊,还是你没有看清楚我提问呢.

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

利用jq的append()追加函数即可实现,如:

html:

<div class="main">
    <input type="button" value="添加" class="btn" />
</div>

JQ:

$(document).ready(function()
    $(".btn").click(function()
        var html = '<div style="width:200px; height:30px; border:1px dashed red; margin-bottom:20px;"></div>';
        $(".main").append(html);
    );
);

参考技术A <html>
<head>
<title>test</title>
<script type="text/javascript" src="jquery.js"></script>
<style>
.divmargin-bottom:5px;background-color:skyblue;
</style>
</head>
<body>
<a href="javascript:void(0)" class="add">生成一个div元素</a>
<div class="tg"></div>
</body>
<script type="text/javascript">
$(function()
$(".add").click(function()
var newObj = $('<div class="div"></div>');
$(".tg").append(newObj);
newObj.text("我是第"+(newObj.index()+1)+"个生成的div").attr("from","new");
);
);
</script>
</html>

参考技术B 使用html()方法添加即可

以上是关于jquery如何在DIV的后面动态添加一个DIV?的主要内容,如果未能解决你的问题,请参考以下文章

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

jquery 如何为动态添加的元素添加样式

如何制作 div,由 jquery 在 woocommerce 结帐表单、动态或完全在表单内添加?

jquery在一个父div中动态添加子div,并在每个子div中显示这是当前第几个子div

如何jquery实现表格数据的动态添加与统计

jquery 动态添加 div 多次触发一个函数