附示例的 jQuery add() 方法


jQuery 中的 add() 方法用于将元素添加到一个现有元素组中。

语法

语法如下所示:

$(selector).add(ele,context)

上方,ele 是选择器表达式,而上下文则指定选择器表达式应从何处开始匹配。

示例

现在让我们看一个实现 jQuery add() 方法的示例:

<!DOCTYPE html>
<html>
<head>
<style>
   .one {
      color: white;
      background-color: blue;
   }
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $("h2").add("p").addClass("one");
   });
</script>
</head>
<body>
<h1>Products</h1>
<h2>Out-of-stock products</h2>
<p>Let us now see some products.</p>
<span>We had Accessories</span><br>
<span>We also had Books, which are now out-of-stock.</span><br>
<p>Electronics products sold completely.</p>
</body>
</html>

输出

这将产生以下输出:

示例

现在让我们看另一个示例:

<!DOCTYPE html>
<html>
<head>
<style>
   .one {
      color: white;
      background-color: orange;
   }
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $("h1").add("h2").add("p").addClass("one");
   });
</script>
</head>
<body>
<h1>Products</h1>
<h2>Out-of-stock products</h2>
<p>Let us now see some products.</p>
<span>We had Accessories</span><br>
<span>We also had Books, which are now out-of-stock.</span><br>
<p>Electronics products sold completely.</p>
</body>
</html>

输出

这将产生以下输出:

更新于:11-11-2019

62 已查看

开启您的 职业

通过完成该课程获得认证

开始
广告