select()

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

.select(handler(eventObject))
  • handler(eventObject) 类型:Function() 。每次事件触发时会执行的函数。
.select([eventData ], handler(eventObject))
  • eventData 类型: PlainObject 。一个对象,它包含的数据键值对映射将被传递给事件处理程序。
  • handler(eventObject) 类型:Function() 。每次事件触发时会执行的函数。
.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="./static/js/jquery-3.5.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").select( function () {
  $("div").text("Something was selected").show().fadeOut(1000);
});
</script>
 
</body>
</html>

Click and drag the mouse to select text in the inputs.

To trigger the select event on all input elements, try:

$("input").select();

上篇: change()

下篇: submit()