返回值:jQueryselect(handler(eventObject))

为 JavaScript 的 "select" 事件绑定一个处理函数,或者触发元素上的该事件。

带有参数的该方法是 .bind('select', handler) 的快捷方式,不带参数的该方法是 .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();
});

在执行完上面的代码后,点击 Trigger the handler 后,同样会显示以下提示:

Handler for .select() called.

此外,在执行完上面的代码后,select 的默认动作也会被执行,即,选中整个文本内容。

检索当前被选中文本的方法,随着浏览器的不同的而不同。有很多 jQuery 插件提供了跨浏览器的解决方案。

示例:

当选中文本框中的内容时,以动画形式显示一个提示信息:

<!DOCTYPE html>
<html>
<head>
<style>
  p { color:blue; }
  div { color:red; }
  </style>
<script src="jquery.min.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>

演示:

示例:

触发所有 input 元素上的 select 事件:

jQuery 代码:
$("input").select();