.select()

.select( handler )返回类型:jQuery

描述:把事件处理函数绑定到“select”JavaScript事件,或者在元素上触发此事件。

此方法在前两种变体中,是.on( "select", handler )的简写,在第三种变体中,是.trigger( "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" ).select(function() {
alert( "Handler for .select() called." );
});

现在,当部分文本被选中时,显示了警告。仅仅设置插入点的位置不会触发此事件。若要手工触发此事件,请不带参数地应用.select()

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

执行了所有代码之后,点击Trigger按钮,也将弹出警告消息:

Handler for .select() called.

此外,还在字段上引发了默认的select动作,所以整个文本域字段将被选中。

在不同的浏览器中,检索当前选中文本的方法各不可同。有些jQuery插件提供了跨平台解决方案。

补充说明:

  • 因为.select()方法是.on( "select", handler )的简写,所以可以用.off( "select" )来分离。

示例:

当输入框中选中了一些文本时:

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>select demo</title>
<style>
p {
color: blue;
}
div {
color: red;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.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" ).select(function() {
$( "div" ).text( "Something was selected" ).show().fadeOut( 1000 );
});
</script>
</body>
</html>

演示:

若要在所有的输入元素中触发select事件,请尝试:

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