jQuery遍历之add()方法

xiaoxiao2021-02-27  188

jQuery是一个合集对象,通过$()方法找到指定的元素合集后可以进行一系列的操作。$()之后就意味着这个合集对象已经是确定的,如果后期需要再往这个合集中添加一新的元素要如何处理?jQuery为此提供add方法,用来创建一个新的jQuery对象 ,元素添加到匹配的元素集合中

.add()的参数可以几乎接受任何的$(),包括一个jQuery选择器表达式,DOM元素,或HTML片段引用。

简单的看一个案例:

操作:选择所有的li元素,之后把p元素也加入到li的合集中

<ul> <li>list item 1</li> <li>list item 3</li> </ul> <p>新的p元素</p>

处理一:传递选择器

$('li').add('p')

处理二:传递dom元素

$('li').add(document.getElementsByTagName('p')[0])

还有一种方式,就是动态创建P标签加入到合集,然后插入到指定的位置,但是这样就改变元素的本身的排列了

$('li').add('<p>新的p元素</p>').appendTo(目标位置) <!DOCTYPE html> <html> <head>     <meta http-equiv="Content-type" content="text/html; charset=utf-8" />     <title></title>     <style>     .left {         width: auto;         height: 150px;     }          .left div {         width: 150px;         height: 120px;         padding: 5px;         margin: 5px;         float: left;         background: #bbffaa;         border: 1px solid #ccc;     }     .right{          background-color:blue;     }     </style>     <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script> </head> <body>     <h2>add方法()</h2>     <div class="left first-div">         <div class="div">             <ul>                 <li>list item 1</li>                 <li>list item 2</li>                 <li>list item 3</li>             </ul>             <p>新的p元素</p>         </div>     </div>     <div class="right"></div>     <br/>     <button>点击:add传递元素标签</button>     <button>点击:add传递html结构</button>     <script type="text/javascript">     $("button:first").click(function() {          //把p元素添加到li的合集中          $('li').add('p').css('background', 'red')     })     </script>     <script type="text/javascript">     $("button:last").click(function() {          //把html结构'<p>新的p元素</p>'          //加入到li的合集中,为了能够在页面上显示          //需要再重新appendTo到指定的节点处          //值得注意:整个结构位置都改变了          $('li').add('<p>新的p元素</p>').appendTo($('.right'))     })     </script> </body> </html>
转载请注明原文地址: https://www.6miu.com/read-13227.html

最新回复(0)