我正在使用javascript创建一个小脚本,以便在我输入时查找/显示数组中的文本。有点像,Google自动推荐工具。
这是Js脚本:
<script>
$(function() {
var availableTags = <?php echo json_encode( $foo ); ?>;
$( "#tags" ).autocomplete({ source: availableTags });
});
</script>
和PHP中的数组
<?php
$foo = array("ambiguious","brown",
"corps","demanding job","eat the pomes","fooling with it");
?>
注意数组中的每个单词的第一个字母是否与其余单词不同,即? 好的,现在当我输入 a 而不是显示带有a(在这种情况下是“模棱两可”)的单词时,它会向我显示所有包含其中的单词。
我考虑让strpos()
搜索相似的字词,但它不起作用。
任何想法都会很好。谢谢。
答案 0 :(得分:1)
查看API:
http://api.jqueryui.com/autocomplete/
示例:使用自定义源回调仅匹配术语的开头
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>autocomplete demo</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.1/themes/base/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.1/jquery-ui.js"></script>
</head>
<body>
<label for="autocomplete">Select a programming language: </label>
<input id="autocomplete">
<script>
var tags = [ "c++", "java", "php", "coldfusion", "javascript", "asp", "ruby" ];
$( "#autocomplete" ).autocomplete({
source: function( request, response ) {
var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( request.term ), "i" );
response( $.grep( tags, function( item ){
return matcher.test( item );
}) );
}
});
</script>
</body>
</html>
答案 1 :(得分:0)
参考我的 LIVE DEMO
List: <input id="myContent" />
var myTags = ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"];
$( "#myContent" ).autocomplete({
source: function( request, response ) {
var matches = $.map(myTags, function(tag) {
if (tag.toUpperCase().indexOf(request.term.toUpperCase()) === 0) {
return tag;
}
});
response(matches);
}
});