jQuery :text 選擇器



jQuery 中的:text 選擇器用於選擇 DOM 中所有型別為“text”的 input 元素。

其主要用途是操作這些特定元素,從而更輕鬆地執行諸如設定值、樣式設定以及向表單中的文字輸入新增事件偵聽器等任務。

語法

以下是 jQuery :text 選擇器的語法:

$(":text")

引數

以下是上述語法的解釋:

  • input: 指定一個選擇器,用於選擇整個文件中的所有文字輸入元素。

示例 1

在以下示例中,我們演示了 jQuery :text 選擇器的基本用法:

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            $('button').click(function() {
                $(':text').val('New Value');
            });
        });
    </script>
</head>
<body>
    <form id="myForm">
        <input type="text" name="input1" placeholder="Enter text here"><br>
        <input type="text" name="input2" placeholder="Enter text here"><br>
        <button>Change Values</button>
    </form>
</body>
</html>

當我們執行程式並單擊按鈕時,所有文字輸入欄位的值將更改為“新值”。

示例 2

在此示例中,我們更改所有文字輸入元素的背景顏色:

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            $('button').click(function() {
                $(':text').css('background-color', 'yellow');
            });
        });
    </script>
</head>
<body>
    <form>
        <label for="input1">Username:</label>
        <input type="text" id="un"><br><br>
        <label for="input2">Password:</label>
        <input type="password" id="pwd"><br><br>
        <button>Change Values</button>
    </form>
</body>
</html>

執行程式後,文字輸入元素的背景顏色將更改為黃色。

jquery_ref_selectors.htm
廣告

© . All rights reserved.