jQuery使用contains過濾器實現精確匹配方法詳解_jquery

來源:互聯網
上載者:User

本文執行個體講述了jQuery使用contains過濾器實現精確匹配的方法。分享給大家供大家參考,具體如下:

:contains 選取器選取包含指定字串的元素。

該字串可以是直接包含在元素中的文本,或者被包含於子項目中。

經常與其他元素/選取器一起使用,來選擇指定的組中包含指定文本的元素,如:

$("p:contains(is)") 表示選擇所有包含 "is" 的 <p> 元素。

再如:

$("p:contains(張三)") 或 $("p:contains("張三")")  表示選擇所有包含 "張三" 的 <p> 元素。

在該選取器裡也可以使用變數來達到選取的目的,如:

$(document).ready(function(){var ddd="John";$("div:contains(‘" + ddd + "‘)").css("color", "#f00");});

我們也可以將jquery的filter方法和contains方法一起使用來達到更加模糊比對的目的,如:

$(document).ready(function(){$(".box").filter(":contains(李)").css("color", "#f00");});

表示將包含”李“的box的文字顏色設定為紅色。

jQuery使用contains過濾器實現精確匹配:

<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head>  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  <title></title>  <!--<script src="jquery.min.js" type="text/javascript"></script>-->  <script src="jquery.min.js" type="text/javascript"></script>  <script type="text/javascript">    $(function () {      //根據select中的option的文本來執行選中      //$("#selectbox option[text='第二項']");      //$("#selectbox option").filter("[text='第二項']");      //上面兩種寫法都是錯誤的      //正確寫法      $("#btn4").click(function () {        var $option =$("#selectbox option:contains('第二項')").map(function(){          if ($(this).text() == "第二項") {            return this;          }        });        alert($option.length > 0 ? "有對象" : "無對象");        $option.attr("selected", true);      });    });  </script></head><body>  <form id="form1">  <div>    <select id="selectbox">      <option value="1">第一項</option>      <option value="2">第二項</option>      <option value="21">第二項1</option>    </select>    <input type="button" id="btn4" value="contains測試" />  </div>  </form></body></html>

更多關於jQuery相關內容感興趣的讀者可查看本站專題:《jQuery拖拽特效與技巧總結》、《jQuery擴充技巧總結》、《jQuery常見經典特效匯總》、《jQuery動畫與特效用法總結》及《jquery選取器用法總結》

希望本文所述對大家jQuery程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.