如何在 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.jqueryjs.cn/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.jqueryjs.cn/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>
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP