jQuery 事件 select() 方法



jQuery 事件select() 方法將事件處理程式繫結到 select 事件,或者在<input><textarea> 元素中的文字被選中時觸發該事件。

語法

以下是 jQuery 事件select() 方法的語法:

$(selector).select(function)

引數

此方法接受一個函式作為引數,如下所述:

  • function (可選) - 當 select 事件發生時執行的可選函式。

返回值

此方法沒有任何返回值。

示例 1

以下是 jQuery 事件select() 方法的基本示例:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
</head>
<body>
    <p>Select the text within the below input field.</p>
    Company Name: <input type="text" value="TutorialsPoint">
    <script>
        $('input').select(function(){
            alert("You select text within the input field.")
        });
    </script>
</body>
</html> 

輸出

上面的程式顯示一個帶有預定義值的輸入欄位。當用戶在此輸入欄位中選擇文字時,瀏覽器螢幕上將出現一個彈出警報訊息:


示例 2

這是 jQuery 事件select() 方法的另一個示例。我們使用此方法在文字區域中的文字被選中時顯示該文字:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
</head>
<body>
    <p>Select the text within the below textarea field.</p>
    Write your valuable Feedback: <br><textarea name="" id="" cols="30" rows="10"></textarea>
    <span></span>
    <script>
        $('textarea').select(function(){
            $('span').text($('textarea').val());
        });
    </script>
</body>
</html>

輸出

執行上述程式後,將顯示一個文字區域欄位。如果您在文字區域中寫入並選擇文字,則選定的文字將顯示在文字區域欄位旁邊:


示例 3

input 欄位內的文字被選中時,更改輸入欄位的背景顏色:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
</head>
<body>
    <p>Select the text within the below input field to change the background color.</p>
    Name: <br><input type="text">
    <span></span>
    <script>
        $('input').select(function(){
            $(this).css({"background-color": "green", "color": "white"});
        });
    </script>
</body>
</html>

輸出

執行上述程式後,它將顯示一個輸入欄位。當輸入中的文字被選中時,背景將變為綠色:


jquery_ref_events.htm
廣告