概述 .select( handler(eventObject) )
返回值:jQuery
描述:为 JavaScript 的 "select" 事件绑定一个处理函数,或者触发元素上的该事件。
这个函数的前两个用法是 .bind('select', handler)
的快捷方式,第3个不带参数的用法是 .trigger('select')
的快捷方式。
当用户在一个元素中进行文本选择时,这个元素上的select
事件就会被触发。此事件只能用在<input type="text">
和<textarea>
。
举例来说,请看下面的HTML:
- <form>
- <input id="target" type="text" value="Hello there" />
- </form>
- <div id="other">
- Trigger the handler
- </div>
这个事件处理程序可以绑定到文本框
- $('#target').select(function() {
- alert('Handler for .select() called.');
- });
现在文本框中任何字符被选择,警告将被显示。仅仅设置插入点的位置将不会触发该事件。应用不带参数的.select()
,我们可以手动触发这个事件:
- $('#other').click(function() {
- $('#target').select();
- });
这些代码执行后,点击触发按钮同样警报显示:
Handler for .select() called.
此外,默认文本域上的select
动作被解除,所以整个文本字段将被选中。
用于检索当前选定文本的方法在各个浏览器中是不同的。jQuery的一个插件都提供跨平台的解决方案。
示例
在输入框中文本被选中时做一件事情时:
- <!DOCTYPE html>
- <html>
- <head>
- <style>
- p { color:blue; }
- div { color:red; }
- </style>
- <script src="http://code.jquery.com/jquery-latest.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>
To trigger the select event on all input elements, try:
- $("input").select();