這篇文章將為大家詳細(xì)講解有關(guān)如何使用JQuery自動(dòng)完成插件Auto Complete,小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。
創(chuàng)新互聯(lián)公司長(zhǎng)期為上1000+客戶提供的網(wǎng)站建設(shè)服務(wù),團(tuán)隊(duì)從業(yè)經(jīng)驗(yàn)10年,關(guān)注不同地域、不同群體,并針對(duì)不同對(duì)象提供差異化的產(chǎn)品和服務(wù);打造開(kāi)放共贏平臺(tái),與合作伙伴共同營(yíng)造健康的互聯(lián)網(wǎng)生態(tài)環(huán)境。為水城企業(yè)提供專(zhuān)業(yè)的成都做網(wǎng)站、網(wǎng)站建設(shè),水城網(wǎng)站改版等技術(shù)服務(wù)。擁有十余年豐富建站經(jīng)驗(yàn)和眾多成功案例,為您定制開(kāi)發(fā)。問(wèn)題
當(dāng)你查找一些特殊的東西,當(dāng)你輸入準(zhǔn)確的詞時(shí),找到它可能是困難的(或者很耗時(shí))。在輸入的時(shí)候展示出結(jié)果(自動(dòng)完成),使查找變得更簡(jiǎn)單。
解決方案
使用JQuery自動(dòng)完成插件,更新現(xiàn)有圖書(shū)列表頁(yè)面上的搜索,當(dāng)用戶鍵入的時(shí)候立即顯示結(jié)果。
討論
自動(dòng)完成插件是不會(huì)象jQuery基本庫(kù)一樣自動(dòng)包含在MVC項(xiàng)目中的,所以需要做的第一件事就是的是下載插件
訪問(wèn)http://jquery.com/。兩個(gè)主要的文件是必需的:JavaScript文件和CSS文件。把新下載的javascript文件放到你MVC應(yīng)用程序的script 文件夾下。CSS文件可以直接添加到您的content目錄。
這個(gè)配方也將介紹在view中使用 rendering sections。在shared文件夾下layout中自動(dòng)添加了2個(gè)javascript文件和1個(gè)css文件。這些是Ajax和不唐突的Ajax和網(wǎng)站主css文件。每次加載的內(nèi)容越多,頁(yè)面視圖加載越慢。與其在每個(gè)頁(yè)面都去包含可能不必要的javascript和css 文件,不如在layout中添加一個(gè)新的RenderSection()。這允許特別的view在
標(biāo)簽去加載特別的javascript或css,但不是每頁(yè)都添加他們。下邊是一個(gè)更新后的Views/Shared/_Layout.cshtml,他使用了一個(gè)新的RenderSection()。
_Mobile @RenderSection("JavaScriptAndCSS", required: false)My MVC Application
@Html.Partial("_LogOnPartial") [ @Html.ActionLink("English", "ChangeLanguage", "Home", new { language = "en" }, null) ] [ @Html.ActionLink("Français", "ChangeLanguage", "Home", new { language = "fr" }, null) ]
- @Html.ActionLink("Home", "Index", "Home", null, new Dictionary
{{ "data-role", "button" }}) - @Html.ActionLink("About", "About", "Home", null, new Dictionary
{ { "data-role", "button" }}) @RenderBody()
主要的CSS文件和核心的JQuery文件被留下來(lái)了,因?yàn)閏ss在每個(gè)也都需要,并且絕大多數(shù)網(wǎng)頁(yè)也需要JQuery。然而新的JQuery文件和不唐突的AJAX不是每個(gè)頁(yè)面都需要的。
現(xiàn)在,有兩種方式使用Autocomplete 插件:
1.在javascript中設(shè)置要搜索的數(shù)據(jù)。
2.當(dāng)用戶輸入時(shí)通過(guò)ajax檢索。
在我使用這個(gè)插件的經(jīng)驗(yàn)看來(lái),我發(fā)現(xiàn)使用解決方案1時(shí)自動(dòng)完成更快。因?yàn)樗⒉恍枰看螐臄?shù)據(jù)庫(kù)中請(qǐng)求數(shù)據(jù)。然而,使用這種解決方案的限制:只有這么多字符,可傳遞到function中,大量的JavaScript可能會(huì)導(dǎo)致用戶的計(jì)算機(jī)上頁(yè)面加載緩慢。經(jīng)過(guò)一些試驗(yàn)和錯(cuò)誤,我已經(jīng)確定神奇的數(shù)字是大約40,000個(gè)結(jié)果。如果結(jié)果數(shù)量超過(guò)此,最好使用選項(xiàng)2;否則,始終堅(jiān)持,因?yàn)樗阉鬟x項(xiàng)1是瞬時(shí),而不是有輕微的延遲。
在這個(gè)例子中,將搜索書(shū)籍,我們沒(méi)有超過(guò)40000,所以將使用選項(xiàng)1。BooksController現(xiàn)在必須更新,以設(shè)置ViewBag為book title。自動(dòng)完成功能需要支持一個(gè)JavaScript數(shù)組的支持,所以書(shū)將管道(|)分開(kāi)。然后在view中,書(shū)將被轉(zhuǎn)換到一個(gè)數(shù)組,使用JavaScript的split()函數(shù)。當(dāng)用戶完成鍵入他們的結(jié)果,他們應(yīng)該有選擇完全匹配標(biāo)題,因此這個(gè)函數(shù)將被更新。如果只有1本書(shū)返回并且用戶執(zhí)行了搜索,它會(huì)自動(dòng)重定向到本書(shū)詳細(xì)介紹頁(yè)面。
我們要在bookcontroller 中更新Index Action 并添加一個(gè)私有方法名為:FormatBooksForAutocomplete。
代碼如下:
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Linq.Dynamic; using System.Web; using System.Web.Mvc; using MvcApplication.Models; using MvcApplication.Utils; using PagedList; namespace MvcApplication.Controllers { public class BooksController : Controller { private BookDBContext db = new BookDBContext(); // // GET: /Books/ [OutputCache(Duration = Int32.MaxValue, SqlDependency = "MvcApplication.Models.BookDBContext:books", VaryByParam = "sortOrder;filter;page")] public ActionResult Index(string sortOrder, string filter, string Keyword, int page = 1) { #region ViewBag Resources ViewBag.Title = Resources.Resource1.BookIndexTitle; ViewBag.CreateLink = Resources.Resource1.CreateLink; ViewBag.TitleDisplay = Resources.Resource1.TitleDisplay; ViewBag.IsbnDisplay = Resources.Resource1.IsbnDisplay; ViewBag.SummaryDisplay = Resources.Resource1.SummaryDisplay; ViewBag.AuthorDisplay = Resources.Resource1.AuthorDisplay; ViewBag.ThumbnailDisplay = Resources.Resource1.ThumbnailDisplay; ViewBag.PriceDisplay = Resources.Resource1.PriceDisplay; ViewBag.PublishedDisplay = Resources.Resource1.PublishedDisplay; ViewBag.EditLink = Resources.Resource1.EditLink; ViewBag.DetailsLink = Resources.Resource1.DetailsLink; ViewBag.DeleteLink = Resources.Resource1.DeleteLink; #endregion #region ViewBag Sort Params ViewBag.TitleSortParam = (sortOrder == "Title") ? "Title desc" : "Title"; ViewBag.IsbnSortParam = (sortOrder == "Isbn") ? "Isbn desc" : "Isbn"; ViewBag.AuthorSortParam = (sortOrder == "Author") ? "Author desc" : "Author"; ViewBag.PriceSortParam = (sortOrder == "Price") ? "Price desc" : "Price"; ViewBag.PublishedSortParam = (String.IsNullOrEmpty(sortOrder)) ? "Published desc" : ""; // Default the sort order if (String.IsNullOrEmpty(sortOrder)) { sortOrder = "Published desc"; } ViewBag.CurrentSortOrder = sortOrder; #endregion var books = from b in db.Books select b; #region Keyword Search if (!String.IsNullOrEmpty(Keyword)) { books = books.Where(b => b.Title.ToUpper().Contains(Keyword.ToUpper()) || b.Author.ToUpper().Contains(Keyword.ToUpper())); // Should we redirect because of only one result? if (books.Count() == 1) { Book book = books.First(); return RedirectToAction("Details", new { id = book.ID }); } } ViewBag.CurrentKeyword = String.IsNullOrEmpty(Keyword) ? "" : Keyword; #endregion #region Filter switch switch (filter) { case "NewReleases": var startDate = DateTime.Today.AddDays(-14); books = books.Where(b => b.Published <= DateTime.Today.Date && b.Published >= startDate ); break; case "ComingSoon": books = books.Where(b => b.Published > DateTime.Today.Date); break; default: // No filter needed break; } ViewBag.CurrentFilter = String.IsNullOrEmpty(filter) ? "" : filter; #endregion books = books.OrderBy(sortOrder); int maxRecords = 1; int currentPage = page - 1; // Get all book titles ViewBag.BookTitles = FormatBooksForAutocomplete(); return View(books.ToPagedList(currentPage, maxRecords)); } private string FormatBooksForAutocomplete() { string bookTitles = String.Empty; var books = from b in db.Books select b; foreach (Book book in books) { if (bookTitles.Length > 0) { bookTitles += "|"; } bookTitles += book.Title; } return bookTitles; } // // GET: /Books/Details/5 public ActionResult Details(int id = 0, string bookTitle = "") { Book book = db.Books.Find(id); return View(book); } // // GET: /Books/Create public ActionResult Create() { return View(); } // // POST: /Books/Create [HttpPost] public ActionResult Create(Book book, HttpPostedFileBase file) { if (ModelState.IsValid) { // Upload our file book.Thumbnail = FileUpload.UploadFile(file); db.Books.Add(book); db.SaveChanges(); return RedirectToAction("Index"); } return View(book); } // // GET: /Books/Edit/5 public ActionResult Edit(int id) { Book book = db.Books.Find(id); return View(book); } // // POST: /Books/Edit/5 [HttpPost] public ActionResult Edit(Book book, HttpPostedFileBase file) { if (ModelState.IsValid) { // Delete old file FileUpload.DeleteFile(book.Thumbnail); // Upload our file book.Thumbnail = FileUpload.UploadFile(file); db.Entry(book).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(book); } // // GET: /Books/Delete/5 public ActionResult Delete(int id) { Book book = db.Books.Find(id); return View(book); } // // POST: /Books/Delete/5 [HttpPost, ActionName("Delete")] public ActionResult DeleteConfirmed(int id) { Book book = db.Books.Find(id); // Delete old file FileUpload.DeleteFile(book.Thumbnail); db.Books.Remove(book); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { db.Dispose(); base.Dispose(disposing); } } }
最后book/index view需要更新去初始化jQuery的自動(dòng)完成。要做的第一件事是使用@節(jié)標(biāo)記,包括必要的JavaScript和CSS文件。接下來(lái),以前創(chuàng)建的搜索文本框更新設(shè)置一個(gè)鍵的IDwordSearch。
最后,JavaScript代碼添加在視圖的底部去在搜索文本框上建立自動(dòng)完成功能。此JavaScript是有意添加在view的底部,以確保完全呈現(xiàn)給用戶,因?yàn)樵谟脩舻碾娔X上建立數(shù)據(jù)是一項(xiàng)工作,Javascript處理可能會(huì)“堵塞”頁(yè)面加載。
(譯者:先呈現(xiàn)數(shù)據(jù)再執(zhí)行javascript,js不是像傳統(tǒng)那樣放在head標(biāo)簽里)
這取決于結(jié)果的數(shù)量。代碼如下:
@model PagedList.IPagedList@if (IsAjax) { Layout = null; } @section JavascriptAndCSS { } @MvcApplication4.Resources.Resource1.BookIndexTitle
@Html.ActionLink("Create New", "Create")
Show: @if (ViewBag.CurrentFilter != "") { @Ajax.ActionLink("All", "Index", new { sortOrder = ViewBag.CurrentSortOrder, Keyword = ViewBag.CurrentKeyword }, new AjaxOptions { UpdateTargetId = "main" }) } else { @:All } | @if (ViewBag.CurrentFilter != "NewReleases") { @Ajax.ActionLink("New Releases", "Index", new { filter = "NewReleases", sortOrder = ViewBag.CurrentSortOrder, Keyword = ViewBag.CurrentKeyword }, new AjaxOptions { UpdateTargetId = "main" }) } else { @:New Releases } | @if (ViewBag.CurrentFilter != "ComingSoon") { @Ajax.ActionLink("Coming Soon", "Index", new { filter = "ComingSoon", sortOrder = ViewBag.CurrentSortOrder, Keyword = ViewBag.CurrentKeyword }, new AjaxOptions { UpdateTargetId = "main" }) } else { @:Coming Soon }
@using (Html.BeginForm()) { @:Search: @Html.TextBox("Keyword", (string)ViewBag.CurrentKeyword, new { id = "KeywordSearch" }) } @Html.Partial("_Paging")@Html.Partial("_Paging")
@foreach (var item in Model) { @Ajax.ActionLink("Title", "Index", new { sortOrder = ViewBag.TitleSortParam, filter = ViewBag.CurrentFilter, Keyword = ViewBag.CurrentKeyword }, new AjaxOptions { UpdateTargetId = "main" }) @Ajax.ActionLink("Isbn", "Index", new { sortOrder = ViewBag.IsbnSortParam, filter = ViewBag.CurrentFilter, Keyword = ViewBag.CurrentKeyword }, new AjaxOptions { UpdateTargetId = "main" }) Summary @Ajax.ActionLink("Author", "Index", new { sortOrder = ViewBag.AuthorSortParam, filter = ViewBag.CurrentFilter, Keyword = ViewBag.CurrentKeyword }, new AjaxOptions { UpdateTargetId = "main" }) Thumbnail @Ajax.ActionLink("Price", "Index", new { sortOrder = ViewBag.PriceSortParam, filter = ViewBag.CurrentFilter, Keyword = ViewBag.CurrentKeyword }, new AjaxOptions { UpdateTargetId = "main" }) @Ajax.ActionLink("Published", "Index", new { sortOrder = ViewBag.PublishedSortParam, filter = ViewBag.CurrentFilter, Keyword = ViewBag.CurrentKeyword }, new AjaxOptions { UpdateTargetId = "main" }) } @Html.DisplayFor(modelItem => item.Title) @Html.DisplayFor(modelItem => item.Isbn) @Html.DisplayFor(modelItem => item.Summary) @Html.DisplayFor(modelItem => item.Author) @Html.DisplayFor(modelItem => item.Thumbnail) @Html.DisplayFor(modelItem => item.Price) @Html.DisplayFor(modelItem => item.Published) @Html.ActionLink("Edit", "Edit", new { id = item.ID }) | @Html.ActionLink("Details", "Details", new { id = item.ID }) | @Html.ActionLink("Delete", "Delete", new { id = item.ID })
為了實(shí)施選項(xiàng)2,一個(gè)Ajax搜索,而不是傳遞數(shù)據(jù)數(shù)組到自動(dòng)完成函數(shù),您可以傳遞一個(gè)URL。URL將需要接受查詢字符串變量:q。這包含用戶輸入的搜索值。這將用于執(zhí)行書(shū)本上包含部分匹配的搜索,并返回以分隔符分隔的字符串。JQuery文檔中含有較多的這樣的成品例子,也有其他的例子,去更新的輸出結(jié)果(可能包括書(shū)的封面的縮略圖)。
關(guān)于“如何使用JQuery自動(dòng)完成插件Auto Complete”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺(jué)得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無(wú)理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國(guó)服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡(jiǎn)單易用、服務(wù)可用性高、性價(jià)比高”等特點(diǎn)與優(yōu)勢(shì),專(zhuān)為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場(chǎng)景需求。