當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


jQuery :contains()用法及代碼示例


jQuery中的:contains()選擇器用於選擇包含指定字符串的元素。

用法:

$(":contains(text)")

參數:該選擇器包含必填的單個參數文本,用於指定要查找的文本。



範例1:本示例使用:contains()選擇器選擇元素。

<!DOCTYPE html> 
<html> 
   <head> 
      <title>jQuery:contains() Selector</title> 
        
      <script src= 
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> 
      </script> 
        
      <!-- Script to use:contains selector -->
      <script> 
         $(document).ready(function(){ 
           $("h3:contains(is)").css("background-color", "green"); 
         }); 
      </script> 
   </head> 
     
   <body> 
      <center> 
         <h1 id="geeks1" style = "color:green;">GeeksForGeeks</h1> 
         <h2 id="geeks2">jQuery:contains() Selector</h2> 
         <h3>Who is your favourite Geek:</h3> 
           
         <div id="choose"> 
             <h3>Geek 1</h3> 
             <h3>Geek 2</h3> 
             <h3>Geek 3</h3> 
         </div> 
      </center> 
   </body> 
</html>

輸出:

範例2:本示例使用:contains()選擇器選擇元素。

<!DOCTYPE html> 
<html> 
   <head> 
      <title>jQuery:contains() Selector</title> 
        
      <script src= 
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> 
      </script> 
        
      <!-- Script to use:contains selector -->
      <script> 
         $(document).ready(function(){ 
           $("h3:contains(Geek)").css("background-color", "green"); 
         }); 
      </script> 
   </head> 
   <body> 
      <center> 
         <h1 id="geeks1" style = "color:green;">GeeksForGeeks</h1> 
         <h2 id="geeks2">jQuery:contains() Selector</h2> 
         <h3>Who is your favourite candidate:</h3> 
           
         <div id="choose"> 
             <h3>Geek 1</h3> 
             <h3>Geek 2</h3> 
             <h3>Geek 3</h3> 
         </div> 
      </center> 
   </body> 
</html>

輸出:




相關用法


注:本文由純淨天空篩選整理自SHUBHAMSINGH10大神的英文原創作品 jQuery | :contains() Selector。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。