您好,登錄后才能下訂單哦!
這篇文章將為大家詳細(xì)講解有關(guān)如何使用JQuery自動(dòng)完成插件Auto Complete,小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。
問(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在<head>標(biāo)簽去加載特別的javascript或css,但不是每頁(yè)都添加他們。
下邊是一個(gè)更新后的Views/Shared/_Layout.cshtml,他使用了一個(gè)新的RenderSection()。
<!DOCTYPE html> <html> <head> <title>_Mobile</title> <link href="@Url.Content(" rel="external nofollow" rel="external nofollow" ~/Content/Site.css")" rel="stylesheet" type="text/css" /> <script src="@Url.Content("~/Scripts/jquery-1.6.2.min.js")" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function () { if (window.innerWidth <= 480) { $("link[rel=stylesheet]").attr({ href: "@Url.Content("~/Content/jquery.mobile-1.0b1.min.css")" }); } }); </script> @RenderSection("JavaScriptAndCSS", required: false) </head> <body> <div class="page" data-role="page"> <div id="header" data-role="header"> <div id="title"> <h2>My MVC Application</h2> </div> <div id="logindisplay" class="ui-bar"> @Html.Partial("_LogOnPartial") [ @Html.ActionLink("English", "ChangeLanguage", "Home", new { language = "en" }, null) ] [ @Html.ActionLink("Français", "ChangeLanguage", "Home", new { language = "fr" }, null) ] </div> <div id="menucontainer" class="ui-bar"> <ul id="menu"> <li>@Html.ActionLink("Home", "Index", "Home", null, new Dictionary<string, object> {{ "data-role", "button" }})</li> <li>@Html.ActionLink("About", "About", "Home", null, new Dictionary<string, object> { { "data-role", "button" }})</li> </ul> </div> </div> <div id="main" data-role="content"> @RenderBody() </div> <div id="footer" data-role="footer"> </div> </div> </body> </html>
主要的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<MvcApplication.Models.Book> @if (IsAjax) { Layout = null; } @section JavascriptAndCSS { <link rel="stylesheet" href="@Url.Content(" rel="external nofollow" rel="external nofollow" ~/Content/jquery.autocomplete.css")" type="text/css" /> <script type="text/javascript" src="@Url.Content("~/Scripts/jquery.autocomplete.js")"></script> <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script> } <h3>@MvcApplication4.Resources.Resource1.BookIndexTitle</h3> <p> @Html.ActionLink("Create New", "Create") </p> <p> 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 } </p> @using (Html.BeginForm()) { @:Search: @Html.TextBox("Keyword", (string)ViewBag.CurrentKeyword, new { id = "KeywordSearch" }) <input type="submit" value="Search" /> } @Html.Partial("_Paging") <table> <tr> <th> @Ajax.ActionLink("Title", "Index", new { sortOrder = ViewBag.TitleSortParam, filter = ViewBag.CurrentFilter, Keyword = ViewBag.CurrentKeyword }, new AjaxOptions { UpdateTargetId = "main" }) </th> <th> @Ajax.ActionLink("Isbn", "Index", new { sortOrder = ViewBag.IsbnSortParam, filter = ViewBag.CurrentFilter, Keyword = ViewBag.CurrentKeyword }, new AjaxOptions { UpdateTargetId = "main" }) </th> <th> Summary </th> <th> @Ajax.ActionLink("Author", "Index", new { sortOrder = ViewBag.AuthorSortParam, filter = ViewBag.CurrentFilter, Keyword = ViewBag.CurrentKeyword }, new AjaxOptions { UpdateTargetId = "main" }) </th> <th> Thumbnail </th> <th> @Ajax.ActionLink("Price", "Index", new { sortOrder = ViewBag.PriceSortParam, filter = ViewBag.CurrentFilter, Keyword = ViewBag.CurrentKeyword }, new AjaxOptions { UpdateTargetId = "main" }) </th> <th> @Ajax.ActionLink("Published", "Index", new { sortOrder = ViewBag.PublishedSortParam, filter = ViewBag.CurrentFilter, Keyword = ViewBag.CurrentKeyword }, new AjaxOptions { UpdateTargetId = "main" }) </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.Title) </td> <td> @Html.DisplayFor(modelItem => item.Isbn) </td> <td> @Html.DisplayFor(modelItem => item.Summary) </td> <td> @Html.DisplayFor(modelItem => item.Author) </td> <td> @Html.DisplayFor(modelItem => item.Thumbnail) </td> <td> @Html.DisplayFor(modelItem => item.Price) </td> <td> @Html.DisplayFor(modelItem => item.Published) </td> <td> @Html.ActionLink("Edit", "Edit", new { id = item.ID }) | @Html.ActionLink("Details", "Details", new { id = item.ID }) | @Html.ActionLink("Delete", "Delete", new { id = item.ID }) </td> </tr> } </table> @Html.Partial("_Paging") <script type="text/javascript"> $(document).ready(function () { var data = "@ViewBag.BookTitles".split("|"); $("#KeywordSearch").autocomplete(data); }); </script>
為了實(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)把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。