本文實(shí)例講述了jquery UI實(shí)現(xiàn)autocomplete在獲取焦點(diǎn)時(shí)得到顯示列表功能。分享給大家供大家參考,具體如下:
在做項(xiàng)目的時(shí)候,客戶有這樣的需求,將以前輸入過的內(nèi)容,在某個(gè)文本框上用列表的形式提示出來,可以選擇,換言之,就如同我們用谷歌搜索,或者百度搜索一樣,輸入一些關(guān)鍵詞,會(huì)自動(dòng)提示,這個(gè)功能就叫autocomplete. 當(dāng)然在 jquery UI 下有 插件,具體下載的地方,搜索就知道了。重點(diǎn)是,我現(xiàn)在的用法,是需要在文本框獲取焦點(diǎn)的時(shí)候,就彈出待選擇的列表。而傳統(tǒng)的是必須在輸入文字之后才出現(xiàn)。經(jīng)過發(fā)現(xiàn),jquery ui autocomplete 用如下方法可以實(shí)現(xiàn)
<!doctype html><html lang="en"><head> <meta charset="utf-8"> <title>jQuery UI Autocomplete - Categories</title> <link rel="stylesheet" href="../../themes/base/jquery.ui.all.css" rel="external nofollow" > <script src="../../jquery-1.9.1.js"></script> <script src="../../ui/jquery.ui.core.js"></script> <script src="../../ui/jquery.ui.widget.js"></script> <script src="../../ui/jquery.ui.position.js"></script> <script src="../../ui/jquery.ui.menu.js"></script> <script src="../../ui/jquery.ui.autocomplete.js"></script> <link rel="stylesheet" href="../demos.css" rel="external nofollow" > <style> .ui-autocomplete-category { font-weight: bold; padding: .2em .4em; margin: .8em 0 .2em; line-height: 1.5; } </style> <script> var data = [ { label: "anders", category: "" }, { label: "andreas", category: "" }, { label: "antal", category: "" }, { label: "annhhx10", category: "Products" }, { label: "annk K12", category: "Products" }, { label: "annttop C13", category: "Products" }, { label: "anders andersson", category: "People" }, { label: "andreas andersson", category: "People" }, { label: "andreas johnson", category: "People" } ]; function dynamicAutocomplete(){ $("#search").autocomplete({ delay:200, autoFocus: false, source: data, minLength: 0, }).focus(function () { $(this).autocomplete("search"); }); } </script></head><body><button onclick="dynamicAutocomplete()">autocomplete</button> <br /><label for="search">Search: </label><input id="search"><div class="demo-description"><p>A categorized search result. Try typing "a" or "n".</p></div></body></html>代碼來源于官網(wǎng)例子,稍稍改動(dòng)了一下,但貌似在IE 下有點(diǎn)問題,選擇某個(gè)選項(xiàng)之后,這個(gè)列表框不消失,還一直存在,比較郁悶。
在google 上搜索了一下,發(fā)現(xiàn)了一篇文章,也講到了這個(gè)問題。后來用如下方法解決,不過是失去焦點(diǎn)的方式做的。
function dynamicAutocomplete(){ $("#search").autocomplete({ minLength: 0, source: data, focus :function () { return false; }, select: function(event, ui){ $this = $(this); setTimeout(function () { $this.blur(); }, 1); } }).focus(function(){ $(this).autocomplete("search"); return false; } ); };
新聞熱點(diǎn)
疑難解答
圖片精選