jQuery自动完成选择事件
在网络世界中,使用自动完成类型输入是一种非常普遍的做法。例如,用户地址栏。为此,jQuery中提供了一个非常常见的UI功能。
在搜索特定值的过程中,jQuery UI的自动完成选择功能为用户提供了一些输入区域的字符串建议,有效地节省了时间。
当用户从预先填充的列表中选择一个选项时,就会触发自动完成选择动作。
一个非常普遍的例子是谷歌建议箱,它被数以百万计的用户使用。这个功能的基本目的是用用户从列表中选择的值来替换文本字段的值。它触发了多个事件,如焦点事件、按键事件或用户输入的变化,这些事件被用来调用不同的函数,返回描述焦点或选定项目的对象。
实现时使用了各种方法,如从数据库表中获取数据以填充用户输入字段的值。它从相关数据库中选择以用户输入的关键词开始的字符串。与动态实现不同,你可以做静态实现。例如,使用一个XML文件或列表从一个变量数组中获取。
select( event, ui ) 这个函数在弹出式列表中的任何选项被选中时都会被触发。它包含两个参数,列在下面。
- event。这个参数提到了由用户触发的事件。
- ui。这个参数提到了包含所选项目的名称和价值属性的对象。
代码 snippet:
$( ".selector" ).autocomplete({
select: function( event, ui ) {}
});
示例 1:
<!doctype html>
<html>
<head>
<title>
jQuery Autocomplete Selection Event
</title>
<link rel="stylesheet" href=
"//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.12.4.js"></script>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js">
</script>
</head>
<body>
<label>Select Technology : </label>
<input id="autocompleteInput">
<script>
var tags = [
"jQuery", "java", "php",
"MySQL", "javascript",
"html", "C#", "C", "MongoDB"
];
$("#autocompleteInput").autocomplete({
source: tags
});
</script>
</body>
</html>
输出:
注意:在上述例子中,源代码实际上定义了用于选择的数据。
示例 2:
<!DOCTYPE html>
<html>
<head>
<title>
jQuery AutoComplete selection
</title>
<link rel="stylesheet" href=
"http://code.jquery.com/ui/1.11.3/themes/ui-lightness/jquery-ui.css"/>
<script src=
"http://code.jquery.com/jquery-2.1.3.js">
</script>
<script src=
"http://code.jquery.com/ui/1.11.2/jquery-ui.js">
</script>
<script>
(document).ready(function() {
var tags = [
"Washington", "Cincinnati",
"Dubai", "Dublin", "Colombo",
"Culcutta"
];
('#input').autocomplete({
source : tags,
select : showResult,
focus : showResult,
change :showResult
})
function showResult(event, ui) {
$('#cityName').text(ui.item.label)
}
});
</script>
</head>
<body>
<form>
<div class="ui-widget">
<label for="input">City Name : </label>
<input id="input"/><br>
Label of City Name: <div id="cityName"></div>
</div>
</form>
</body>
</html>
输出:
注意:从上面两个代码例子中,你可以观察到源参数占用了字符串选项的列表,如数组或函数回调的结果。
jQuery是一个开源的JavaScript库,它简化了HTML/CSS文档之间的交互,它以其 “少写多做 “的理念而广为人知。
你可以通过学习这个jQuery教程和jQuery实例,从基础开始学习jQuery。