如何在 jQuery 中將堆疊中的先前元素集合新增到當前集合?
jQuery是一個功能豐富的 JavaScript 庫。我們可以藉助 jQuery 執行許多操作,否則這些操作需要編寫大量程式碼。它使DOM操作、事件處理、動畫、ajax 等變得非常容易。
在本教程中,我們將學習如何將堆疊中的先前元素集合新增到當前集合。jQuery 保持對匹配堆疊執行的更改的內部堆疊。當呼叫DOM遍歷函式或方法時,新元素會被推入堆疊。因此,要使用之前的堆疊元素,需要呼叫addBack()方法。
語法
我們在下面的語法中對列表項進行了著色
<ul> <li>Item 1</li> <li>Item 2</li> <li id="mark">Item 3</li> <li>Item 4</li> <li>Item 5</li> </ul>
以及 jQuery 程式碼。
$('#mark').prevAll().addBack().css('color', 'green')
演算法
首先,jQuery 識別具有指定 ID 的元素,然後初始化一個新的堆疊並將該元素壓入堆疊。
現在,第二個函式告訴我們選擇之前的全部專案。因此,jQuery 刪除當前專案並新增之前的列表項。
最後,我們呼叫addBack()函式,該函式將具有 ID 標記的第三個列表項新增到堆疊中。最後,CSS 應用於所有三個元素 1、2 和 3。
示例 1
在下面的示例中,我們有一些專案的列表。然後 jQuery 使用addBack()函式並演示了addBack()函式在兩個列表中的區別。
<!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <title>TutorialsPoint | jQuery</title> </head> <body> <center> <h4>Add the previous set of elements on the stack to the current set in jQuery</h4> </center> <div> <p>Before addBack()</p> <ul> <li>list item 1</li> <li>list item 2</li> <li id="mark1">list item 3</li> <li>list item 4</li> <li>list item 5</li> </ul> </div> <div> <p>After addBack()</p> <ul> <li>list item 1</li> <li>list item 2</li> <li id="mark2">list item 3</li> <li>list item 4</li> <li>list item 5</li> </ul> </div> <script> $('#mark1').prevAll().css({ color: 'blue', 'font-weight': 'bold' }) $('#mark2').prevAll().addBack().css({ color: 'blue', 'font-weight': 'bold' }) </script> </body> </html>
示例 2
在下面的示例中,我們有兩個 div 容器,我們使用相同的addBack()函式選擇之前的容器。
<!DOCTYPE html> <html lang="en"> <head> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <title>TutorialsPoint | jQuery</title> <style> p, div { margin: 5px; padding: 5px; color: #ff3d3d; } .border { border: 2px solid #44aaad; } .background { background: #ffe260; } .left, .right { width: 40%; float: left; } .right { margin-left: 2%; } </style> </head> <body> <center> <h1>TutorialsPoint</h1> <strong>How to add the previous set of elements on the stack to the current set in jQuery?</strong> </center> <div class="left"> <p><strong>Before<code>addBack()</code></strong></p> <div class="before-addback"> <p>TutorialsPoint</p> <p>jQuery</p> </div> </div> <div class="right"> <p><strong>After<code>addBack()</code></strong></p> <div class="after-addback"> <p>TutorialsPoint</p> <p>jQuery</p> </div> </div> <script> $('.left, .right').find('div, div > p').addClass('border') // First Part $('.before-addback').find('p').addClass('background') // Second Part $('.after-addback').find('p').addBack().addClass('background') </script> </body> </html>
廣告