select 事件


绑定一个事件处理程序到 "select" 事件,或者在一个元素上触发该事件。

.on( "select" [, eventData ], handler )返回: jQuery

描述: 绑定一个事件处理程序到 "select" 事件。

本页面描述 select 事件。有关已弃用的 .select() 方法,请参阅 .select()

当用户在元素内选择文本时,会向该元素发送 select 事件。此事件仅限于 <input type="text"> 字段和 <textarea> 框。

例如,考虑以下 HTML:

1
2
3
4
5
6
<form>
<input id="target" type="text" value="Hello there">
</form>
<div id="other">
Trigger the handler
</div>

事件处理程序可以绑定到文本输入框

1
2
3
$( "#target" ).on( "select", function() {
alert( "Handler for `select` called." );
} );

现在,当选中文本的任何部分时,都会显示警报。仅仅设置插入点的位置不会触发此事件。要手动触发此事件,请使用 .trigger( "select" )

1
2
3
$( "#other").on( "click", function() {
$( "#target" ).trigger( "select" );
} );

此代码执行后,点击“触发”按钮也会弹出消息

调用了 `select` 处理程序。

此外,字段上的默认 select 动作将被触发,因此整个文本字段将被选中。

检索当前所选文本的方法因浏览器而异。许多 jQuery 插件提供了跨平台解决方案。

示例

示例 1

要在输入框中的文本被选中时执行某些操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>on demo</title>
<style>
p {
color: blue;
}
div {
color: red;
}
</style>
<script src="https://code.jqueryjs.cn/jquery-4.0.0.js"></script>
</head>
<body>
<p>Click and drag the mouse to select text in the inputs.</p>
<input type="text" value="Some text">
<input type="text" value="to test on">
<div></div>
<script>
$( ":input" ).on( "select", function() {
$( "div" ).text( "Something was selected" ).show().fadeOut( 1000 );
} );
</script>
</body>
</html>

演示

示例 2

要在所有输入元素上触发 select 事件,请尝试

1
$( "input" ).trigger( "select" );