jquery autocomplete使用教程(动态绑定以及ajax实现)
注意我用的是jquery autocomplete plugin,不是jquery ui中的jquery autocomplete,jquery autocomplete plugin的使用很简单,如下:
<html> <head> <title>PHP点点通-</title> <script type="text/javascript" src="/js/jquery-1.4.2.min.js"></script> <script type="text/javascript" src="/js/jquery.autocomplete.min.js"></script> <link href="/js/jquery.autocomplete.css" /> <script type="text/javascript"> var emails = [ { name: "Molly", to: "molly@yahoo.com" }, { name: "mckee", to: "mckee@phpddt.com" }, ]; $(function() { $('#keyword').autocomplete(emails, { max: 12, //列表里的条目数 minChars: 0, //自动完成激活之前填入的最小字符 width: 400, //提示的宽度,溢出隐藏 scrollHeight: 300, //提示的高度,溢出显示滚动条 matchContains: true, //包含匹配,就是data参数里的数据,是否只要包含文本框里的数据就显示 autoFill: false, //自动填充 formatItem: function(row, i, max) { return i + 'http://www.phpddt.com/' + max + ':"' + row.name + '"[' + row.to + ']'; }, formatMatch: function(row, i, max) { return row.name + row.to; }, formatResult: function(row) { return row.to; } }).result(function(event, row, formatted) { alert(row.to); }); }); </script> </head> <body> <form runat="server"> <div> <input /> <input value="GetValue" type="button" /> </div> </form> </body> </html>
说明如下:
formatItem作用在于可以格式化列表中的条目。
formatMatch是配合formatItem使用,作用在于,由于使用了formatItem,所以条目中的内容有所改变,而我们要匹配的是原始的数据,所以用formatMatch做一个调整,使之匹配原始数据,
formatResult是定义最终返回的数据,比如我们还是要返回原始数据,而不是formatItem过的数据。
因为我动态clone了DOM,也可以动态绑定autocomplete:
<script type='text/javascript' src='js/jquery-autocomplete/jquery.autocomplete.js'></script> <link type="text/css" href="js/jquery-autocomplete/jquery.autocomplete.css" /> <script> $(function(){ $("input.departs").live("keydown",function(){ //departs的json格式数据 $(this).autocomplete(<?php echo $departs?>, { width: 250, max: 100, scroll: true, scrollHeight: 300, formatItem: function(row, i, max) { return row.name; }, formatResult: function(row) { return row.fixed_number; } }).result(function(event, row) { $(this).parent().siblings().find("input[name='deputy_name[]']").val(row.contact_name); $(this).parent().siblings().find("input[name='fixed_number[]']").val(row.fixed_number); $(this).parent().siblings().find("input[name='mobile_phone[]']").val(row.mobile_phone); $(this).parent().siblings().find("input[name='email[]']").val(row.email); }); }); }); </script>
使用ajax返回数据实现autocomplete也很简单:
<script type="text/javascript"> $(document).ready(function () { $.ajax({ type: "POST", contentType: "application/json", url: "AjaxPage.aspx/GetAllHints", data: "{}", dataType: "json", success: function (msg) { var datas = eval('(' + msg.d + ')'); $("#txtIput").autocomplete(datas, { formatItem: function (row, i, max) { return "<table><tr><td>" + row.Key + "</td><td><font>约" + row.Value + "www.phpddt.com</font> </td></tr></table>"; }, formatMatch: function(row, i, max){ return row.Key; } }); } }); }); </script>
jquery autocomplete 使用总结就这么多,有几个案例摘自网络。
转载请注明地址: 尊重他人劳动成果就是尊重自己!
jQuery