jQuery :contains() 選擇器



jQuery 中的:contains() 選擇器用於選擇包含指定文字字串的元素。要匹配的文字是區分大小寫的,這意味著“Hello”和“hello”不被認為是相同的。它選擇在其內容中的任何位置包含指定文字的元素,包括子元素。

語法

以下是 jQuery 中 :contains 選擇器的語法:

$(":contains(text)")

引數

“text” 是要在元素中搜索的字串。此字串區分大小寫。

示例 1

在下面的示例中,我們使用 :contains 選擇器來突出顯示包含單詞“Tutorialspoint”的段落:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("p:contains('Tutorialspoint')").css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <p>Tutorialspoint.</p>
    <p>This one will not be highlighted.</p>
    <p>Tutorialspoint.</p>
</body>
</html>

執行上述程式後,所有包含“Tutorialspoint”單詞的<p>元素都將以黃色背景突出顯示。

示例 2

在此示例中,我們選擇包含特定文字“item”的“列表項”:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("li:contains('item')").css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <ul>
        <li>This is the first item.</li>
        <li>Another list item.</li>
        <li>This will not change (background-color will not be added).</li>
        <li>Final item in the list.</li>
    </ul>
</body>
</html>

執行上述程式後,所有包含單詞“item”的列表項都將以黃色背景突出顯示。

示例 3

在此示例中,我們選擇包含文字“Tutorialspoint”的<div>元素:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("div:contains('Tutorialspoint')").css("font-weight", "bold");
        });
    </script>
</head>
<body>
    <div>I work in Tutorialspoint.</div>
    <div>This will not be bold.</div>
    <div>Tutorialspoint is in Hyderabad.</div>
</body>
</html>

執行上述程式後,包含文字“Tutorialspoint”的<div>元素將以黃色背景突出顯示。

jquery_ref_selectors.htm
廣告