jquery DOM外部插入insertAfter()与insertBefore()

    xiaoxiao2021-03-25  78

    与内部插入处理一样,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 http-equiv="Content-type" content="text/html; 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> <h2>通过insertBefore与insertAfter添加元素</h2> <button id="bt1">点击通过jQuery的insertBefore添加元素</button> <button id="bt2">点击通过jQuery的insertAfter添加元素</button> <div class="aaron"> <p class="test1">测试insertBefore,不支持多参数</p> </div> <div class="aaron"> <p class="test2">测试insertAfter,不支持多参数</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>
    转载请注明原文地址: https://ju.6miu.com/read-22795.html

    最新回复(0)