jQuery 插入insertAfter()与insertBefore()

与内部插入处理一样,jQuery由于内容目标的位置不同,然增加了2个新的方法insertAfter与insertBefore

before()和.insertBefore()实现同样的功能。主要的区别是语法——内容和目标的位置。 对于before()选择表达式在函数前面,内容作为参数,而.insertBefore()刚好相反,内容在方法前面,它将被放在参数里元素的前面

after()和.insertAfter() 实现同样的功能。主要的不同是语法——特别是(插入)内容和目标的位置。 对于after()选择表达式在函数的前面,参数是将要插入的内容。对于 .insertAfter(), 刚好相反,内容在方法前面,它将被放在参数里元素的后面

before、after与insertBefore。insertAfter的除了目标与位置的不同外,后面的不支持多参数处理

注意事项:

insertAfter将JQuery封装好的元素插入到指定元素的后面,如果元素后面有元素了,那将后面的元素后移,然后将JQuery对象插入;

insertBefore将JQuery封装好的元素插入到指定元素的前面,如果元素前面有元素了,那将前面的元素前移,然后将JQuery对象插入;

下面我们来写一段代码:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"></script>
    <style>
    .test1 {
        background: #bbffaa;
    }
    
    .test2 {
        background: yellow;
    }
    </style>
</head>

<body>
    <button id="bt1">insertBefore添加元素</button>
    <button id="bt2">insertAfter添加元素</button>
    <div class="aaron">
        <p class="test1">php 中文网</p>
    </div>
    <div class="test2">php.cn</p>
    </div>
    <script type="text/javascript">
    $("#bt1").on('click', function() {
        //在test1元素前后插入集合中每个匹配的元素
        //不支持多参数
        $('<p style="color:red">测试insertBefore方法增加</p>', '<p style="color:red">多参数</p>').insertBefore($(".test1"))
    })
    </script>
    <script type="text/javascript">
    $("#bt2").on('click', function() {
        //在test2元素前后插入集合中每个匹配的元素
        //不支持多参数
        $('<p style="color:red">测试insertAfter方法增加</p>', '<p style="color:red">多参数</p>').insertAfter($(".test2"))
    })
    </script>
</body>

</html>

大家测试一下,看有什么样的差别

继续学习
||
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <script src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"></script> <style> .test1 { background: #bbffaa; } .test2 { background: yellow; } </style> </head> <body> <button id="bt1">insertBefore添加元素</button> <button id="bt2">insertAfter添加元素</button> <div class="aaron"> <p class="test1">php 中文网</p> </div> <div class="test2">php.cn</p> </div> <script type="text/javascript"> $("#bt1").on('click', function() { //在test1元素前后插入集合中每个匹配的元素 //不支持多参数 $('<p style="color:red">测试insertBefore方法增加</p>', '<p style="color:red">多参数</p>').insertBefore($(".test1")) }) </script> <script type="text/javascript"> $("#bt2").on('click', function() { //在test2元素前后插入集合中每个匹配的元素 //不支持多参数 $('<p style="color:red">测试insertAfter方法增加</p>', '<p style="color:red">多参数</p>').insertAfter($(".test2")) }) </script> </body> </html>
提交重置代码
章节
笔记
提问
课件
反馈
捐赠

JQuery 基础入门教程

高并发千万级数据库系统解决方案
  • 推荐课程
  • 评论
  • 问答
  • 笔记
  • 课件下载