附示例的 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 已檢視

開啟您的 職業

透過完成該課程獲得認證

開始
廣告
© . All rights reserved.