广告
返回顶部
首页 > 资讯 > 前端开发 > VUE >如何使用JQuery自动完成插件Auto Complete
  • 485
分享到

如何使用JQuery自动完成插件Auto Complete

2024-04-02 19:04:59 485人浏览 薄情痞子
摘要

这篇文章将为大家详细讲解有关如何使用Jquery自动完成插件Auto Complete,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。问题当你查找一些特殊的东西,当你输入准

这篇文章将为大家详细讲解有关如何使用Jquery自动完成插件Auto Complete,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

问题

当你查找一些特殊的东西,当你输入准确的词时,找到它可能是困难的(或者很耗时)。在输入的时候展示出结果(自动完成),使查找变得更简单。

解决方案

使用JQuery自动完成插件,更新现有图书列表页面上的搜索,当用户键入的时候立即显示结果。

讨论

自动完成插件是不会象jQuery基本库一样自动包含在mvc项目中的,所以需要做的第一件事就是的是下载插件
访问Http://jquery.com/。两个主要的文件是必需的:javascript文件和CSS文件。把新下载的javascript文件放到你MVC应用程序的script 文件夹下。CSS文件可以直接添加到您的content目录。

这个配方也将介绍在view中使用 rendering sections。在shared文件夹下layout中自动添加了2个javascript文件和1个css文件。这些是ajax和不唐突的Ajax和网站主css文件。每次加载的内容越多,页面视图加载越慢。与其在每个页面都去包含可能不必要的javascript和css 文件,不如在layout中添加一个新的RenderSection()。这允许特别的view在<head>标签去加载特别的javascript或css,但不是每页都添加他们。

下边是一个更新后的Views/Shared/_Layout.cshtml,他使用了一个新的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&ccedil;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文件被留下来了,因为css在每个也都需要,并且绝大多数网页也需要JQuery。然而新的JQuery文件和不唐突的AJAX不是每个页面都需要的。

现在,有两种方式使用Autocomplete 插件:

1.在javascript中设置要搜索的数据。

2.当用户输入时通过ajax检索。

在我使用这个插件的经验看来,我发现使用解决方案1时自动完成更快。因为它并不需要每次从数据库中请求数据。然而,使用这种解决方案的限制:只有这么多字符,可传递到function中,大量的JavaScript可能会导致用户的计算机上页面加载缓慢。经过一些试验和错误,我已经确定神奇的数字是大约40,000个结果。如果结果数量超过此,最好使用选项2;否则,始终坚持,因为搜索选项1是瞬时,而不是有轻微的延迟。

在这个例子中,将搜索书籍,我们没有超过40000,所以将使用选项1。BooksController现在必须更新,以设置ViewBag为book title。自动完成功能需要支持一个JavaScript数组的支持,所以书将管道(|)分开。然后在view中,书将被转换到一个数组,使用JavaScript的split()函数。当用户完成键入他们的结果,他们应该有选择完全匹配标题,因此这个函数将被更新。如果只有1本书返回并且用户执行了搜索,它会自动重定向到本书详细介绍页面。

我们要在bookcontroller 中更新Index Action 并添加一个私有方法名为: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的自动完成。要做的第一件事是使用@节标记,包括必要的JavaScript和CSS文件。接下来,以前创建的搜索文本框更新设置一个键的IDwordSearch。

最后,JavaScript代码添加在视图的底部去在搜索文本框上建立自动完成功能。此JavaScript是有意添加在view的底部,以确保完全呈现给用户,因为在用户的电脑上建立数据是一项工作,Javascript处理可能会“堵塞”页面加载。

(译者:先呈现数据再执行javascript,js不是像传统那样放在head标签里)

这取决于结果的数量。代码如下:

@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
}
&nbsp; | &nbsp;
@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
}
&nbsp; | &nbsp;
@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>

为了实施选项2,一个Ajax搜索,而不是传递数据数组到自动完成函数,您可以传递一个URL。URL将需要接受查询字符串变量:q。这包含用户输入的搜索值。这将用于执行书本上包含部分匹配的搜索,并返回以分隔符分隔的字符串。JQuery文档中含有较多的这样的成品例子,也有其他的例子,去更新的输出结果(可能包括书的封面的缩略图)。

关于“如何使用JQuery自动完成插件Auto Complete”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

--结束END--

本文标题: 如何使用JQuery自动完成插件Auto Complete

本文链接: https://www.lsjlt.com/news/77529.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 如何使用JQuery自动完成插件Auto Complete
    这篇文章将为大家详细讲解有关如何使用JQuery自动完成插件Auto Complete,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。问题当你查找一些特殊的东西,当你输入准...
    99+
    2022-10-19
  • VsCode插件自动生成注释插件koroFileHeader使用教程
    目录VsCode插件自动生成注释插件koroFileHeader使用PS:vscode使用‘koroFileHeader‘插件生成注释插件安装配置插件插件使用...
    99+
    2023-01-17
    VsCode自动生成注释插件koroFileHeader使用 VsCode koroFileHeader生成注释
  • jquery如何使用skitter插件
    小编给大家分享一下jquery如何使用skitter插件,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!下载地址:http://w...
    99+
    2022-10-19
  • jQuery插件datatables如何使用
    这篇文章主要介绍了jQuery插件datatables如何使用的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇jQuery插件datatables如何使用文章都会有所收获,下面我们一起来看看吧。jQuery 的插...
    99+
    2023-07-04
  • jquery插件Jplayer如何使用
    本篇内容介绍了“jquery插件Jplayer如何使用”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!现在从需求上来了解它的使用方法吧。第一个...
    99+
    2023-07-04
  • 如何利用python自动完成工作
    如何利用python自动完成工作,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。没有什么能比学以致用让学习变得更有动力的了。不知道大家在工作中有没有一些工作需要重复的点击鼠标,因...
    99+
    2023-06-02
  • 如何使用jQuery表单验证插件和日历插件
    这篇文章主要为大家展示了“如何使用jQuery表单验证插件和日历插件”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“如何使用jQuery表单验证插件和日历插件”这...
    99+
    2022-10-19
  • jQuery中如何使用tip提示插件
    小编给大家分享一下jQuery中如何使用tip提示插件,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!效果图:代码如下:<!DOCTYPE html> <html...
    99+
    2022-10-19
  • AngularJS中如何使用jQuery的zTree插件
    这篇文章主要介绍了AngularJS中如何使用jQuery的zTree插件的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇AngularJS中如何使用jQuery的zTree插件文章都会有所收获,下面我们一起来看...
    99+
    2023-07-04
  • 使用MyBatis-Generator如何自动生成映射文件
    目录MyBatis-Generator自动生成映射文件1、使用cmd命令方式生成2、使用maven方式生成3、如果开发工具为eclipse自动生成MyBatis映射文件工具问题MyB...
    99+
    2022-11-13
  • 如何使用jQuery插件imgAreaSelect实现截图功能
    这篇文章主要介绍了如何使用jQuery插件imgAreaSelect实现截图功能的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇如何使用jQuery插件imgAreaSelect实现截图功能文章都会有所收获,下面...
    99+
    2023-07-04
  • jQuery如何实现在HTML文档加载完毕后自动执行某个事件
    这篇文章给大家分享的是有关jQuery如何实现在HTML文档加载完毕后自动执行某个事件的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。具体如下:原来onchange=“fucnti...
    99+
    2022-10-19
  • 如何使用Vue完成移动端apk项目
    这篇文章将为大家详细讲解有关如何使用Vue完成移动端apk项目,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。我们项目使用的是Vue和Vant组件,详情都可以看官网哦VantVue完整项目视频链接目录结构:...
    99+
    2023-06-15
  • AngularJS如何使用angular.bootstrap完成模块手动加载
    这篇文章主要介绍AngularJS如何使用angular.bootstrap完成模块手动加载,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!本文实例分析了AngularJS使用angu...
    99+
    2022-10-19
  • 如何使用maven自定义插件开发
    这篇文章主要介绍了如何使用maven自定义插件开发的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇如何使用maven自定义插件开发文章都会有所收获,下面我们一起来看看吧。Maven 插件的命名规范一般来说,我们会...
    99+
    2023-07-02
  • ionic2中如何使用自动生成器
    这篇文章给大家分享的是有关ionic2中如何使用自动生成器的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。ionic generator是命令行的功能,ionic2自动帮我们创建应...
    99+
    2022-10-19
  • 如何使用python自动生成日历
    这篇文章给大家分享的是有关如何使用python自动生成日历的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。python是什么意思Python是一种跨平台的、具有解释性、编译性、互动性和面向对象的脚本语言,其最初的设...
    99+
    2023-06-14
  • Win8系统的IE如何设置自动完成的项目不用手动填写
      我们在上网时经常会遇到一些诸如地址栏、表单等项目需要手动填写信息,不少用户觉得这样很不方便。其实Win8的IE浏览器能够设置自动完成的项目,下面是具体操作方法。   步骤   1.打开Internet选...
    99+
    2022-06-04
    自动完成 如何设置 项目
  • 如何使用ES6写全屏滚动插件
    这篇文章主要为大家展示了“如何使用ES6写全屏滚动插件”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“如何使用ES6写全屏滚动插件”这篇文章吧。1)前面的话现在已...
    99+
    2022-10-19
  • Android在layout xml中如何使用ViewStub完成动态加载
    这篇文章主要介绍了Android在layout xml中如何使用ViewStub完成动态加载,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。一、Layout XML文件常见的两...
    99+
    2023-05-30
    android layout xml
软考高级职称资格查询
推荐阅读
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作