jQuery insert insertAfter() and insertBefore()
Same as internal insertion processing, jQuery has added two new methods insertAfter and insertBefore due to different locations of content targets
before() and .insertBefore() to achieve the same function. The main difference is syntax - content and placement of goals. For before(), the selection expression is in front of the function, and the content is used as a parameter, while .insertBefore() is just the opposite, the content is in front of the method, and it will be placed in front of the element in the parameter
after() and .insertAfter () achieves the same function. The main difference is the syntax - specifically the placement of (inserted) content and targets. For after(), the selection expression is in front of the function, and the parameter is the content to be inserted. For .insertAfter(), On the contrary, if the content is in front of the method, it will be placed after the elements in the parameters
before, after and insertBefore. In addition to the difference in target and position, insertAfter does not support multi-parameter processing
Notes:
insertAfter inserts the JQuery-encapsulated element behind the specified element. If there are element, then move the following element back, and then insert the JQuery object;
insertBefore inserts the JQuery-encapsulated element in front of the specified element. If there is an element in front of the element, then move the previous element in front of it. Move, and then insert the JQuery object;
Let’s write a piece of code:
<!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>
Let’s test it and see what difference there is