ASP-NET-jQuery-秘籍-全-
ASP.NET jQuery 秘籍(全)
零、前言
jQuery 是一个轻量级的 JavaScript 库,它改变了 web 应用中客户端脚本的格局。 它由 John Resig 在 2006 年开发,由于它的跨浏览器兼容性和用更少的代码做更多的事情的能力,它在网络上掀起了一股风暴。 这个库得到了活跃的开发人员社区的支持,并且在过去几年里得到了显著的发展。 使用 jQuery 简化了许多客户机脚本任务,例如事件处理、嵌入动画、编写支持 Ajax 的页面等等,并增加了最终用户的交互体验。 它的可扩展插件架构使开发人员能够在核心库的基础上构建额外的功能。
学习 jQuery 并在 ASP 中使用它.NET 应用是 asp.net 中不可缺少的技能.NET 开发者。 本书试图通过探索各种方法来传授这一技能,以快速、简单地解决 ASP 中一些常见问题.NET 4.6 的应用。
这本书的内容
第 1 章,第 2 章 ASP. jQuery 入门.NET,描述了菜谱的下载,并在 ASP 中包含 jQuery.NET 4.6 Web 和 MVC 应用。 它讨论了 CDN, NuGet 包管理器,以及在 Visual Studio 中调试 jQuery 代码。
第二章,在 ASP 中使用 jQuery 选择器 NET 控件,描述了各种可以用来操纵 ASP. NET 控件的 jQuery 选择器.NET 控制。 这些选择器可以根据 ID、CSS 类、HTML 标记、属性或文档中的位置选择控件。
第三章、描述了使用 jQuery处理不同类型事件的方法,如鼠标、键盘和表单事件。 它还解释了事件委托和事件分离。
第 4 章,ASP 中 DOM 遍历和操作 NET描述了遍历文档的技术,例如访问父元素、子元素或兄弟元素。 它还教授在运行时添加和删除元素的操作策略。
第五章、ASP 中的视觉效果 asp.net 网站,讨论了在 ASP 上创建不同类型动画效果的方法.NET 控件,如 Panel、AdRotator、TreeView、Menu 和 GridView。 诸如放大、滑动和褪色等效果将在本章中介绍。
第六章,在 ASP 中使用图形 NET Sites,讨论了处理图像的方法,并解释了图像的缩放、滚动和淡出等效果。 本章还探讨了一些实用工具,如图片库、图像预览和 5 星评级控制。
第七章,Ajax Using jQuery,解释了 Ajax 如何调用页面方法,web 服务,WCF 服务,web API, MVC 控制器和 HTTP 处理程序。
第 8 章,创建和使用 jQuery 插件,演示了如何在项目中创建插件。 它还描述了如何使用节点包管理器(Node Package Manager, NPM)和 Bower 来下载和管理第三方插件。
第 9 章,ASP. jQuery 的实用菜谱.NET Sites,总结了这本书解决常见现实问题的多种方法。 你可以在:https://www.packtpub.com/sites/default/files/downloads/4836OT_Chapter_09找到本章。
你需要什么来写这本书
要使用这本书中的例子,你需要具备以下条件:
- Visual Studio 2015
- MS SQL Server 2014
- Northwind 数据库
- jQuery 库
- jQuery UI 库
- 一个 web 浏览器
- 节点包管理器(NPM)
- 鲍尔
一些菜谱还需要使用第三方 jQuery 插件,比如验证和循环插件。
这本书是写给谁的
这本书是为 ASP 编写的.NET 开发人员希望使用 jQuery 编写客户端脚本以实现跨浏览器兼容性。 没有 ASP 的先验知识.NET 或 jQuery 是必需的,并且每个菜谱都是自包含的,并以一种简单易懂的方式进行解释。 本书中的代码示例是用 c#和 VB 提供的。 熟悉 Visual Studio 和 MS SQL Server 优先,但不是强制要求。
各章节
在这本书中,你会发现几个经常出现的标题(准备好了,怎么做…… 它是如何工作的…… ,还有更多… ,并参见 also)。
为了清楚地说明如何完成一个食谱,我们使用以下这些部分:
准备
本节将告诉您食谱中需要的内容,并描述如何设置食谱所需的任何软件或任何初步设置。
怎么做……
本节包含遵循食谱所需的步骤。
How it works…
本节通常包括对前一节中所发生的事情的详细解释。
还有更多的…
为了使读者更了解该食谱,本部分包含了关于该食谱的附加信息。
参见 also
本节提供了有关该菜谱的其他有用信息的有用链接。
约定
在这本书中,你会发现许多不同的文本样式来区分不同种类的信息。 下面是这些风格的一些例子以及对它们含义的解释。
文本中的代码字、数据库表名、文件夹名、文件名、文件扩展名、路径名、虚拟 url、用户输入和 Twitter 句柄如下所示:“在下载页面上,也有一个以.min.map扩展名可用的地图文件。 有时,当缺陷出现在生产环境中,需要进行故障排除时,使用缩小的文件进行调试可能会很困难。”
一段代码设置如下:
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
ScriptManager.ScriptResourceMapping.AddDefinition("jquery", New ScriptResourceDefinition() With {
.Path = "~/Scripts/jquery-2.1.4.min.js",
.DebugPath = "~/Scripts/jquery-2.1.4.js",
.CdnPath = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js",
.CdnDebugPath = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.js",
.CdnSupportsSecureConnection = True,
.LoadSuccessExpression = "window.jQuery"})
End Sub
当我们希望提请您注意代码块的特定部分时,相关的行或项以粗体显示:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnableCdn="true">
<Scripts>
<asp:ScriptReference Name="jquery" />
</Scripts>
</asp:ScriptManager>
任何命令行输入或输出都写如下:
bower install jquery-validation
新词语、重要词语以粗体显示。 您在屏幕上看到的文字,例如菜单或对话框中,会出现如下文本:“单击页面右侧的下载 jQuery按钮(在前面的截图中突出显示)。 这将打开带有可用文件列表的下载页面。”
注意事项
警告或重要说明显示在这样的框中。
提示
提示和技巧是这样的。
读者反馈
我们欢迎读者的反馈。 让我们知道你对这本书的看法——你喜欢或不喜欢这本书。 读者反馈对我们来说很重要,因为它能帮助我们开发出你能真正从中获益最多的游戏。
要向我们发送一般性的反馈,只需发送电子邮件<[feedback@packtpub.com](mailto:feedback@packtpub.com)>,并在邮件的主题中提到这本书的标题。
如果有一个主题,你有专业知识,你有兴趣写或贡献一本书,请参阅我们的作者指南www.packtpub.com/authors。
客户支持
现在,你已经自豪地拥有了一本书,我们有一些东西可以帮助你从购买中获得最大的好处。
示例代码下载
您可以从您的帐户http://www.packtpub.com下载本书的示例代码文件。 如果您在其他地方购买这本书,您可以访问http://www.packtpub.com/support并注册,将文件直接通过电子邮件发送给您。
你可以按以下步骤下载代码文件:
- 使用您的电子邮件地址和密码登录或注册我们的网站。
- 将鼠标指针悬停在顶部的SUPPORT标签上。
- 点击代码下载&勘误表。
- 在Search框中输入书名。
- 选择您想要下载代码文件的书。
- 从下拉菜单中选择你购买这本书的地方。
- 点击代码下载。
下载文件后,请确保使用最新版本的解压或解压缩文件夹:
- WinRAR / 7-Zip for Windows
- Mac 的 Zipeg / iZip / unarx
- 7-Zip / PeaZip for Linux
下载这本书的彩色图片
我们还为您提供了一个 PDF 文件,其中有彩色图像的屏幕截图/图表使用在这本书。 彩色图像将帮助您更好地理解输出中的变化。 您可以从https://www.packtpub.com/sites/default/files/downloads/ASPNET_jQuery_Cookbook_Second_Edition_ColorImages.pdf下载此文件。
勘误表
尽管我们已经竭尽全力确保内容的准确性,但错误还是会发生。 如果你在我们的书中发现错误——也许是文本或代码上的错误——如果你能向我们报告,我们将不胜感激。 通过这样做,您可以使其他读者免受挫折,并帮助我们改进这本书的后续版本。 如果您发现任何勘误表,请访问http://www.packtpub.com/submit-errata,选择您的图书,点击勘误表提交表格链接,并输入您的勘误表详细信息。 一旦您的勘误表被核实,您的提交将被接受,勘误表将被上载到我们的网站或添加到该标题的勘误表部分下的任何现有勘误表列表中。
要查看之前提交的勘误表,请访问https://www.packtpub.com/books/content/support并在搜索字段中输入书名。 所需资料将出现在勘误表部分。
盗版
在互联网上盗版受版权保护的材料是一个贯穿所有媒体的持续问题。 在 Packt,我们非常重视版权和授权的保护。 如果您在互联网上发现我们的作品以任何形式的非法拷贝,请立即提供我们的地址或网站名称,以便我们进行补救。
请通过<[copyright@packtpub.com](mailto:copyright@packtpub.com)>与我们联系,并提供疑似盗版资料的链接。
我们感谢您的帮助,保护我们的作者和我们的能力,为您带来有价值的内容。
问题
如果您对本书的任何方面有任何疑问,您可以通过<[questions@packtpub.com](mailto:questions@packtpub.com)>与我们联系,我们将尽力解决问题。
一、开始学习 ASP.NET 和 jQuery
在本章中,我们将介绍以下食谱:
- jQuery 下载:jQuery.com
- 理解 jQuery 的 CDN
- 使用 NuGet 包管理器下载 jQuery
- 将 jQuery 添加到空 ASP 中.NET web 项目使用一个脚本块
- 将 jQuery 添加到空 ASP 中。 . NET web 项目使用 ScriptManager 控件
- 将 jQuery 添加到 ASP。 网主页
- 将 jQuery 编程添加到 web 表单
- 理解默认 Web 应用模板中的 jQuery 引用
- 在一个 web 项目中使用 jQuery 的 Hello World
- 在 ASP 中绑定 jQuery.NET MVC
- 使用 CDN 在 MVC 中加载 jQuery
- Hello World 用 ASP。 使用 jQuery 实现 asp.net MVC
- 在 Visual Studio 中调试 jQuery 代码
简介
作为一个网页开发者,你经常需要在你的网站中包含一些功能,这使得用 JavaScript 编写客户端脚本是不可避免的。 让客户端脚本为所有浏览器产生相同的响应一直是一个挑战。 jQuery 可以帮助您克服这个困难。 从本质上讲,jQuery 是一个强大的 JavaScript 库,可以在所有浏览器上工作,比如 Internet Explorer (IE)、Firefox、Safari、Chrome、Opera、iOS 和 Android。 它消除了开发人员为了在不同平台上维护他们的客户机脚本所面临的痛苦。
jQuery 之所以流行,不仅因为支持跨浏览器,还因为它包含了开发人员可以插入和播放的特性。 它改变了开发人员编写客户机脚本的方式。 除了减少需要编写的代码量之外,它还提供了遍历 DOM、事件处理、构建动画和 AJAX 等特性。
本章讨论如何获取库和其他支持文件。 它的目标是涵盖在 ASP 中包含和使用 jQuery 的不同方面.NET 4.6 web 应用项目,如 web 表单和 mvc。
注意事项
本书基于 Visual Studio 2015 和 jQuery 2.1.4。 这些脚本已经在 Internet Explorer 11.0.96、Mozilla Firefox 38.0.1 和谷歌 Chrome 47.0.2526 中进行了测试。
如果您熟悉下载 jQuery 并将其包含在您的 ASP。 。NET 应用,你可以跳过这一章,继续学习第 2 章,中使用 jQuery 选择器和 ASP 操作控件的方法.NET 控件。
从 jQuery 下载
本食谱解释了如何在您的系统上下载 jQuery 以及,以及要使用的版本/版本和所需的支持文件。
准备
下载 jQuery 的步骤如下:
-
Launch any web browser and enter the URL http://www.jquery.com to access the jQuery home page:
![Getting ready]()
-
Click on the Download jQuery button (highlighted in the preceding screenshot) on the right-hand side of the page. This opens up the download page with a list of available files, as shown in the following screenshot:
![Getting ready]()
怎么做……
在撰写本文时,jQuery 有两个主要版本:
- 版本 1. x
- 版本 2. x
虽然两个主要版本的Application Programming Interface(API)是相同的,但区别在于对某些浏览器的支持。 的 2。 x 行不支持旧的浏览器,如 IE 6、7 和 8,而 1。 X 行继续提供这种支持。 因此,如果您应用的终端用户不使用旧浏览器,您可以下载 2。 x 版本。
jQuery 库由单个 JavaScript(.js)文件组成,可以以以下格式下载:
- 未压缩格式:在开发环境或调试代码时使用。
- 压缩格式:这是在生产(即发布)环境中使用。 它是紧凑的和使用低带宽。 它通常被称为缩小版。
要下载该文件,只需右键单击所需的版本 1。 x 或 2。 X,以及所需的格式:未压缩或压缩。 将文件保存在您选择的位置,如下图所示:

注意以下 jQuery 库的命名约定:
| |未压缩的
|
压缩
|
| --- | --- | --- |
| 版本 1。 x | jquery - 1. x.x.js | jquery - 1. x.x.min.js |
| 版本 2 x | jquery - 2. x.x.js | jquery - 2. x.x.min.js |
压缩(缩小)版本与未压缩版本明显不同,因为有.min.js扩展名。 缩小后的文件使用代码优化技术,例如删除空白和注释,以及将变量名减少到一个字符。 这个版本很难阅读,所以在调试时首选未压缩版本。
在下载页面上,还有一个扩展名为.min.map的地图文件。 有时,当生产环境中出现了需要进行故障排除的错误时,使用缩小的文件进行调试可能会很困难。 映射文件简化了这个过程。 它将压缩文件映射回其未构建状态,以便在调试期间,体验与使用未压缩版本类似。
参见 also…
了解 jQuery 的 CDN配方。
了解 jQuery 的 CDN
内容分发网络(CDN)通过大型分布式系统为用户提供内容。 使用 CDN 的优点是提高了性能。 当使用 CDN 检索 jQuery 库时,如果之前下载过文件,将不会重新下载。 这可以帮助您提高响应时间。
怎么做……
以下 cdn 可用于 jQuery 文件:
- jQuery 的 CDN 由 MaxCDN 提供
- 谷歌的 CDN
- 微软的 CDN
- CDNJS CDN 的
- jsDelivr CDN 的
为了将 jQuery 包含在一个网页上,可以使用相应 CDN 的 URL,这样文件就可以直接从 CDN 提供,而不是使用本地副本。 下表总结了 jQuery 文件各自的 CDN url:
|CDN
|
URL
|
| --- | --- |
| jQuery 的 CDN | 版本 2.x:http://code.jquery.com/jquery-2.x.x.js``http://code.jquery.com/jquery-2.x.x.min.js版本 1.xhttp://code.jquery.com/jquery-1.x.x.js``http://code.jquery.com/jquery-1.x.x.min.js |
| The 谷歌 CDN | 版本 2.x:https://ajax.googleapis.com/ajax/libs/jquery/2.x.x/jquery.js``https://ajax.googleapis.com/ajax/libs/jquery/2.x.x/jquery.min.js版本 1.xhttps://ajax.googleapis.com/ajax/libs/jquery/1.x.x/jquery.js``https://ajax.googleapis.com/ajax/libs/jquery/1.x.x/jquery.min.js |
| Microsoft CDN | 版本 2.x:http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.x.x.js``http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.x.x.min.js``http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.x.x.min.map版本 1.xhttp://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.x.x.js``http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.x.x.min.js``http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.x.x.min.map |
| CDNJS CDN | 版本 2.x:https://cdnjs.cloudflare.com/ajax/libs/jquery/2.x.x/jquery.js``https://cdnjs.cloudflare.com/ajax/libs/jquery/2.x.x/jquery.min.js``https://cdnjs.cloudflare.com/ajax/libs/jquery/2.x.x/jquery.min.map版本 1.xhttps://cdnjs.cloudflare.com/ajax/libs/jquery/1.x.x/jquery.js``https://cdnjs.cloudflare.com/ajax/libs/jquery/1.x.x/jquery.min.js``https://cdnjs.cloudflare.com/ajax/libs/jquery/1.x.x/jquery.min.map |
| jsdeliverr CDN | 版本 2.x:https://cdn.jsdelivr.net/jquery/2.x.x/jquery.js``https://cdn.jsdelivr.net/jquery/2.x.x/jquery.min.js``https://cdn.jsdelivr.net/jquery/2.x.x/jquery.min.map版本 1.xhttps://cdn.jsdelivr.net/jquery/1.x.x/jquery.js``https://cdn.jsdelivr.net/jquery/1.x.x/jquery.min.js``https://cdn.jsdelivr.net/jquery/1.x.x/jquery.min.map |
为新版本使用 cdn
注意,当启动 jQuery 库的新版本时,cdn 可能没有最新的文件,因为第三方通常需要几天的时间来更新它们的文件。 对于新版本,在下载之前一定要检查可用的版本。
How it works…
cdn 由位于全球战略位置的数据中心中的服务器组成。 当客户端从 CDN 请求资源时,地理上最接近客户端的服务器处理该请求。 这些服务器也被称为边缘服务器。 除此之外,边缘服务器有缓存机制来服务各种资产。 所有这些都可以帮助您提高客户端的响应时间。
参见 also
使用 NuGet 包管理器下载 jQuery配方
使用 NuGet 包管理器下载 jQuery
NuGet 是一个可以在 Visual Studio 中使用的软件包管理器。 它简化了安装和升级包的过程。 这个食谱演示了如何使用 NuGet 下载 jQuery 库。
准备
要为一个特定的项目启动 NuGet,请访问Tools|NuGet Package Manager|Manage NuGet Packages for Solution… 如下截图所示:

或者,在Solution Explorer选项卡中右键单击项目,选择管理 NuGet 包。
怎么做……
使用 NuGet Manager 下载 jQuery 的步骤如下:
-
In the NuGet Package Manager, as shown in the following screenshot, select the jQuery package from the left-hand side panel. In the right-hand side panel, select the Version that you would like to use in your web project from the drop-down menu. Click on the Install button:
![How to do it…]()
提示
在 NuGet 中搜索包
如果在左侧面板中看不到 jQuery,你需要在 NuGet Manager 屏幕左上角的搜索框中键入
jQuery来搜索它。 -
在提示确认时单击OK,以便对解决方案进行必要的更改。
How it works…
NuGet 包管理器在Scripts文件夹中下载所选版本的 jQuery。 删除Scripts文件夹中存在的任何其他版本。 Scripts文件夹将如下截图所示:

NuGet 下载的文件如下(版本号以后可能会有变化):
- jquery-2.1.4.intellisense.js
- 调试版本:jquery-2.1.4.js
- 发布版本:jquery-2.1.4.min.js
- map 文件:jquery-2.1.4.min。 地图
参见 also
下载 jQuery from jQuery.comrecipe
在空 ASP 中添加 jQuery.NET web 项目使用一个脚本块
创建 ASP.NET 4 .6 Web 应用,Visual Studio 提供了各种现成的模板,如 Empty、Web Forms、MVC、WebAPI 等等。 此菜谱将使用 Empty 模板,该模板为开发人员提供一个空项目结构,该结构仅包含web.config文件。
提示
下载示例代码
您可以从您的帐户http://www.packtpub.com下载本书的示例代码文件。 如果你在其他地方购买了这本书,你可以访问 http://www.packtpub.com/support 并注册,让文件直接通过电子邮件发给你。
准备
以下是使用空模板创建项目的步骤:
-
Create a new project in Visual Studio by going to File | New | Project..., as shown in the following screenshot:
![Getting ready]()
提示
网站还是网络项目?
除了创建一个新项目,你还可以创建一个新网站。 与项目不同,网站不包含用于跟踪应用中的单个文件的集合项目文件。 要创建一个网站,请到File|New|Web Site… 。 这将启动New Website对话框,其中包含可用模板列表。 选择ASP.NET 空网站模板。
-
This will launch the New Project dialog box, as shown in the following screenshot. From the left-hand side panel, select your desired programming language, Visual C# or Visual Basic, and then, select ASP.NET Web Application from the middle panel:
![Getting ready]()
-
在name字段中输入
WebApplication1(或任何合适的名称)。 点击浏览按钮到想要保存应用的位置。 点击OK上的。 -
This will launch the Select a template dialog box, as shown in the following screenshot:
![Getting ready]()
-
From ASP.NET 4.6 Templates, select Empty, and click on OK. Visual Studio will create an empty project in the Solution Explorer tab, as shown in the following screenshot:
![Getting ready]()
注意事项
在其余的菜谱中,当被要求使用 Empty 模板创建 Web Application 项目时,请遵循本节中列出的步骤。
怎么做……
下面是使用脚本块包含 jQuery 的步骤:
-
JavaScript files are usually placed in a folder named Scripts in the web application. So, in the Solution Explorer tab, right-click on the project and go to Add | New Folder from the menu:
![How to do it…]()
-
Rename the folder to
Scripts. Now, right-click on the Scripts folder, and go to Add | Existing Item... as shown in the following screenshot:![How to do it…]()
-
Now, browse to the location where you have saved the downloaded copy of the jQuery files (refer to the Downloading jQuery from jQuery.com recipe), and click on OK. It is recommended that you add both the uncompressed and compressed versions. The Scripts folder will be updated, as shown in the following screenshot:
![How to do it…]()
-
Next, create a new web form in the project by right-clicking on the project and navigating to Add | New Item.... From the dialog box, select Web Form, and enter a suitable name for the web form, such as
Default.aspx:![How to do it…]()
-
To use jQuery on the web form, simply drag and drop the required jQuery file, that is, uncompressed or compressed on the web form. Or alternatively, include the following
<script>tag in the<head>element:对于开发模式,代码如下:
<script src="Scripts/jquery-2.1.4.js"></script>对于发布模式,代码如下:
<script src="Scripts/jquery-2.1.4.min.js"></script>![How to do it…]()
参见 also
从 jQuery.comrecipe 下载 jQuery【T4
在空 ASP 中添加 jQuery.NET web 项目使用 ScriptManager 控件
使用脚本块将 jQuery 添加到 web 表单中有一些缺点。 如果应用升级到使用 jQuery 的最新版本,那么所有带有<script>标签的 web 表单都需要更改。 其次,从开发环境中的未压缩版本切换到发布环境中的压缩版本应该手动处理,因此很容易出错。 使用 ASP.NETScriptManager控件可以帮助您克服这个问题。 它也可以直接从 CDN 加载 jQuery,而不是使用本地副本。
准备
- 创建一个新的ASP。 按照中列出的步骤将 jQuery 添加到空的 ASP. NET Web 应用项目中使用空的模板.NET web 项目使用脚本块配方。 将项目命名为
WebApplication2(或任何其他合适的名称)。 - 按照前面配方中的步骤将 jQuery 库(未压缩和压缩格式)添加到Scripts文件夹中。
- 按照以下步骤向项目中添加一个新的 web 表单。
怎么做……
下面是将 jQuery 添加到 ASP 的步骤.NET web 项目使用ScriptManager控件:
-
以Design模式打开网页表单。
-
启动工具箱。 这可以通过两种方式来实现。 从页面顶部的File菜单中,转到View|Toolbox。 或者,使用快捷键Ctrl+Alt+X。
-
Go to Toolbox | AJAX Extensions, and drag and drop the ScriptManager control onto the form:
![How to do it…]()
-
Right-click on the project in the Solution Explorer tab, and go to Add | New Item.... From the dialog box, select Global Application Class. This will add the Global.asax file to the project:
![How to do it…]()
注意事项
Global.asax文件是一个可选文件,它驻留在应用的根目录中,响应应用和会话级别的事件,例如启动和结束应用或会话。 -
Open the
Global.asaxfile and include the following namespace at the top of the page:对于 VB,代码如下:
Imports System.Web.UI对于 c#,代码如下:
using System.Web.UI; -
In the
Application_Startevent in theGlobal.asaxfile, add the following code to create a script that maps to jQuery:对于 VB,代码如下:
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs) ScriptManager.ScriptResourceMapping.AddDefinition("jquery", New ScriptResourceDefinition() With { .Path = "~/Scripts/jquery-2.1.4.min.js", .DebugPath = "~/Scripts/jquery-2.1.4.js", .CdnPath = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js", .CdnDebugPath = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.js", .CdnSupportsSecureConnection = True, .LoadSuccessExpression = "window.jQuery"}) End Sub对于 c#,代码如下:
protected void Application_Start(object sender, EventArgs e) { ScriptManager.ScriptResourceMapping.AddDefinition("jquery", new ScriptResourceDefinition { Path = "~/Scripts/jquery-2.1.4.min.js", DebugPath = "~/Scripts/jquery-2.1.4.js", CdnPath = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js", CdnDebugPath = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.js", CdnSupportsSecureConnection = true, LoadSuccessExpression = "window.jQuery" }); } -
Open the
Default.aspxweb form in the Source mode. Add the followingScriptReferenceto theScriptManagercontrol:<asp:ScriptManager ID="ScriptManager1" runat="server"> <Scripts> <asp:ScriptReference Name="jquery" /> </Scripts> </asp:ScriptManager>注意事项
当使用
ScriptManager控件向 jQuery 库添加引用时,jQuery 代码应该放在ScriptManager控件之后,即在 jQuery 引用声明之后; 否则,页面将抛出错误。 同样需要注意的是,ScriptManager控件应该驻留在<form>元素中。 -
将
ScriptManager控件的EnableCdn属性设置为true,从 CDN 中检索 jQuery 文件。
How it works…
下面是 ScriptManager 控件的工作方式:
-
ScriptManager控件可以用来加载 JavaScript 文件,例如 jQuery 库。 这可以通过在ScriptManager控件中添加ScriptReference到 jQuery 来实现,如下所示: -
However, we require to define this mapping. This can be done in the
|Global.asaxfile using aScriptResourceDefinitionobject, An exposes the following properties:Property
|
Description
|
| --- | --- |
|Path| This is the path of script resources |
|DebugPath| This is the development/debugging path of script resources |
|CdnPath| This is from CDN script resources |
|CdnDebugPath| This is the development/debugging path from CDN script resources |
|CdnSupportsSecureConnection| This indicates that when accessing a page using a secure connection, Whether to use HTTPS mode search resources |
|LoadSuccessExpression| This is a JavaScript expression that is used to check whether the JavaScript file has been successfully loaded. | -
在
Global.asax中定义的ScriptResourceDefinition对象命名为jquery。 控件使用相同的名称在 web 表单上加载引用。 -
In the development/debug mode, the script is served from
DebugPathwhile in the release mode, it is served fromPath.提示
在开发/调试和发布模式下运行
要在开发/调试模式下运行应用,将
web.config中的<compilation>元素的debug属性设置为true,如下所示:<system.web> <compilation debug="true"/> ….. </system.web>当
debug属性设置为false时,应用将以发布模式运行。 -
如果
EnableCdn设置为true,则脚本从 CDN 路径提供,即在开发/调试模式下从CdnDebugPath提供,在发布模式下从CdnPath提供。 -
The
LoadSuccessExpressionproperty renders an inline script to load the library from the local path in the event of a CDN failure. By right-clicking on the web page and viewing the source, note that theScriptManagercontrol adds a fall back mechanism when the CDN is unavailable and files are served locally instead:![How it works…]()
参见 also
将 jQuery 添加到空 ASP. php 中.NET web 项目使用一个脚本块配方
在 asp.net 中添加 jQuery。 网主页
母版页用于在网站中实现统一的外观和感觉。 它们在所有内容页面上保持一致的布局。 在母版页中包含 jQuery 可以确保所有使用母版页的内容页在默认情况下也包含这个库。 本食谱将演示如何做到这一点。
注意事项
母版页是一个 ASP。 带有.Master扩展名的。NET 文件。 它在布局的顶部有一个@Master指令,而不是在普通的.aspx页面中的@Page指令。
准备
-
创建一个新的ASP。 按照中列出的步骤将 jQuery 添加到空的 ASP. NET Web 应用项目中使用空的模板.NET web 项目使用脚本块配方。 将项目命名为
WebApplicationWithMaster(或任何其他合适的名称)。 -
按照前面配方中的步骤将 jQuery 库(未压缩和压缩格式)添加到Scripts文件夹中。
-
In the Solution Explorer tab, right-click on the project, and go to Add | New Item.... This will launch a dialog box, as shown in the following screenshot. From the dialog box, select Web Forms Master Page. Name the Master Page
Default.Master, and click on Add:![Getting ready]()
-
To add a web form—that is, a content page—to the project, right-click on the project in the Solution Explorer tab again, and navigate to Add | New Item.... From the dialog box, this time select Web Form with Master Page, as shown in the following screenshot. Name the web form
Default.aspx, and click on Add:![Getting ready]()
-
This will launch a dialog box so that you can select the Master Page. From the dialog box, as shown in the following screenshot, select the Master Page to be associated with the content page, and click on OK:
![Getting ready]()
怎么做……
将 jQuery 集成到 asp.net 中.NET 主页,遵循这些步骤:
-
Open the
Default.MasterMaster Page in the Source mode, and add a reference to the jQuery library using either the<script>block (refer to the Adding jQuery to an empty ASP.NET web project using a script block recipe) or theScriptManagercontrol (refer to the Adding jQuery to an empty ASP.NET web project using the ScriptManager control recipe), as shown in the following screenshot:![How to do it…]()
![How to do it…]()
注意事项
当使用
<script>块时,jQuery引用最好放在<head>元素中。当使用
ScriptManager控件时,该控件最好放在ContentPlaceHolder之前的<form>元素中,然后将 jQuery 代码添加到内容页面中。Global.asax文件也应该更新,以便添加所需的ScriptResourceDefinition,,如向空 ASP 中添加 jQuery 所述.NET web 项目使用 ScriptManager 控件配方。 -
所需的 jQuery 代码现在可以添加到
Default.aspxweb 表单中的ContentPlaceHolder(与ID = "ContentPlaceHolder1"一起)中。
How it works…
在运行应用时,当Default.aspx内容页面被加载时,来自 Master 页面的 HTML 标记将引用添加到 jQuery 库。 这使得内容页可以使用 jQuery,因此任何 jQuery 代码都可以执行。
要检查 jQuery 引用是否已添加到页面中,请运行该项目并在浏览器中启动Default.aspx。 右键单击浏览器窗口中的页面并选择查看源。 jQuery 引用将会在页面上看到,如下截图所示:

参见 also
将 jQuery 添加到空 ASP. php 中。 . NET web 项目使用 ScriptManager 控件配方
通过编程方式将 jQuery 添加到 web 表单中
除了使用脚本块和ScriptManager控件将 jQuery 添加到 web 表单中之外,后台代码文件还可以发出所需的脚本代码。 本食谱将演示如何做到这一点。
准备
- 创建一个 ASP。 文件|新|项目|ASP. NET Web 应用项目 NET Web 应用。 选择空的模板。 将项目命名为
WebApplicationWithPageLoad(或任何其他合适的名称)。 - 添加一个新的Web 表单到项目中,并将其命名为
Default.aspx。 - 将 jQuery 库文件添加到Scripts文件夹中。
- 从解决方案资源管理器选项卡,导航到Default.aspx.vb(VB)或Default.aspx.cs(c#),这是 web 表单的代码后置文件。 打开这个文件。
怎么做……
在Default.aspx.vb的Page_Load事件处理程序中,使用RegisterClientScriptInclude方法在页面上生成一个脚本块,如下所示:
对于 VB,代码如下:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Page.ClientScript.RegisterClientScriptInclude("jquery", Page.ResolveUrl("~/Scripts/jquery-2.1.4.js"))
End Sub
对于 c#,代码如下:
protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterClientScriptInclude("jquery", Page.ResolveUrl("~/Scripts/jquery-2.1.4.js"));
}
How it works…
RegisterClientScriptInclude方法需要两个参数:密钥和 URL。 它在<form>元素中添加带有 jQuery 库路径的脚本块,如下面的截图所示。 Page.ResolveUrl方法用于返回一个相对于站点根目录的 URL:

由于 jQuery 库添加到<form>元素,所有的 jQuery 代码应该写在<form>元素而不是<head>元素,最好是页面的末尾之前关闭<form>元素。
参见 also
将 jQuery 添加到空 ASP. php 中.NET web 项目使用一个脚本块配方
理解 web 应用默认模板中 jQuery 的引用
到目前为止,所有的示例都使用了空的模板来实现的 ASP.NET Web 应用项目。 当使用一个非空的内置 web 应用模板时,asp.net.NET 使用ScriptManager控件在母版页中添加对 jQuery 库的引用。 本食谱将指导您了解该映射的重要细节。
怎么做……
下面是创建 ASP 的步骤.NET web 应用使用默认的 web 应用模板:
-
创建一个新项目导航到文件|新|项目… 。 在对话框中,选择ASP.NET Web 应用。 将项目命名为
DemoWebApplication(或其他合适的名称),然后单击OK。 -
A new dialog box will be launched. Select Web Forms from the available templates. Note that the Web Forms checkbox is checked by selecting the Web Forms template (refer to the following screenshot) and click on OK as shown in the following screenshot:
![How to do it...]()
-
Open the
Site.MasterMaster Page in the Source mode, as shown in the following screenshot:![How to do it...]()
-
注意,添加到
<form>元素的ScriptManager控件对 jQuery 的引用如下:
How it works…
当你按照之前的步骤,这是如何将 web 应用映射到 jQuery 库:
-
ScriptManager控件根据web.config:<compilation debug="true"/>中
<compilation>元素的debug属性在开发版本和发布版本之间切换 jQuery 库。 -
当
debug属性为true时,使用未压缩版本。 当debug为false时,使用缩小版。 -
The default template is shipped with the
AspNet.ScriptManager.jQuerypackage. This package adds the followingScriptMappingsto jQuery in thePreApplicationStartmethod of the application as follows:对于 c#,代码如下:
string str = "2.4.1"; ScriptManager.ScriptResourceMapping.AddDefinition("jquery", new ScriptResourceDefinition { Path = "~/Scripts/jquery-" + str + ".min.js", DebugPath = "~/Scripts/jquery-" + str + ".js", CdnPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-" + str + ".min.js", CdnDebugPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-" + str + ".js", CdnSupportsSecureConnection = true, LoadSuccessExpression = "window.jQuery" });注意事项
默认的 Web Forms 模板添加了 Microsoft CDN URL,如前面的代码所示。
-
当
ScriptManager控件的EnableCdn属性设置为true时,在发布模式和开发模式中分别使用CdnPath和CdnDebugPath来服务来自 Microsoft CDN 的脚本:<asp:ScriptManager runat="server" EnableCdn="true"> -
However, if the CDN is down or if the application is offline, the
ScriptManagercontrol will include a fallback mechanism to serve the local copy of jQuery, as shown in the following screenshot:![How it works…]()
-
To change the CDN to another, for example Google CDN, we need to change
ScriptResourceMappingin theRegisterBundlesmethod inBundleConfig, as shown in the following code. This module/class is located in theApp_Startfolder:对于 VB,代码如下:
ScriptManager.ScriptResourceMapping.AddDefinition("jquery", New ScriptResourceDefinition() With { .Path = "~/Scripts/jquery-2.1.4.min.js", .DebugPath = "~/Scripts/jquery-2.1.4.js", .CdnPath = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js", .CdnDebugPath = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.js", .CdnSupportsSecureConnection = True, .LoadSuccessExpression = "window.jQuery"})对于 c#,代码如下:
ScriptManager.ScriptResourceMapping.AddDefinition("jquery", new ScriptResourceDefinition { Path = "~/Scripts/jquery-2.1.4.min.js", DebugPath = "~/Scripts/jquery-2.1.4.js", CdnPath = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js", CdnDebugPath = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.js", CdnSupportsSecureConnection = true, LoadSuccessExpression = "window.jQuery" }); -
By running the page and viewing the source in the browser window, note that Microsoft CDN is replaced with Google CDN as required:
![How it works…]()
-
Open the
Global.asaxpage to view the registration of bundles in theApplication_Startevent handler as follows:对于 VB,代码如下:
BundleConfig.RegisterBundles(BundleTable.Bundles)对于 c#,代码如下:
BundleConfig.RegisterBundles(BundleTable.Bundles);
参见 also
将 jQuery 添加到空 ASP. php 中。 . NET web 项目使用 ScriptManager 控件配方
在 web 项目中使用 jQuery 实现 Hello World
直到,所有的菜谱都已经演示了将 jQuery 库添加到网页的不同方法。 这是使页面就绪 jquery 的第一步。 在本教程中,让我们继续下一步:在一个脚本块中编写 jQuery 代码来操作 web 表单中的控件。 通过在 web 表单上操作Label控件,我们将在 web 页面上显示一个简单的 Hello World 消息。
准备
- 通过File|New|project|ASP 创建一个 Web 应用项目.NET Web 应用。 选择空模板。 将项目命名为
HelloWorld(或任何其他合适的名称)。 - 添加一个新的Web 表单到项目中。
- 将 jQuery 库文件添加到Scripts文件夹中。
- 使用你选择的任何方法在 web 表单上添加一个 jQuery 库的引用。
- 在Design模式中打开 web 窗体,通过导航到Toolbox|Standard控件,拖放Label控件。 更改
Label控件的属性如下:
怎么做……
如果一个 jQuery 引用被添加到<head>元素中,那么在<head>元素中包含下面的<script>块。 否则,包含<form>元素,最好在<form>标签关闭之前:
<script type="text/javascript">
$(document).ready(function () {
var fontStyle = "Arial";
var fontSize = 28;
$("#<%=lblMessage.ClientID%>").css("font-family", fontStyle);
$("#<%=lblMessage.ClientID%>").css("font-size", fontSize);
$("#<%=lblMessage.ClientID%>").text("Hello World!!");
});
</script>
How it works…
下面是打印 Hello World 的步骤!! 在一个 web 项目中使用 jQuery:
-
在前面的 jQuery 代码中,
$符号用于实例化jQuery对象。 -
当 DOM 准备好时,触发
.ready()函数。 它通常用于在页面上执行所需的 jQuery 代码。 -
控件可以从 jQuery 代码中通过 ASP 访问.NET 的
ClientID属性和 jQuery 的#identifier选择器。 -
Using the
.css()property of thejQueryobject, the font style, size, and text of theLabelcontrol are manipulated so that the following output is displayed on running the application:![How it works…]()
参见 also
Hello World 在 ASP 中的应用。 asp.net MVC 使用 jQuery配方
在 ASP 中绑定 jQuery.NET MVC
模型视图控制器(MVC)是一种设计模式,它将设计(模型)、表示(视图)和操作(控制器)分离开来。 由于 Visual Studio 在开发人员中非常流行,它提供了用于创建 MVC 项目的现成模板。
与 web 表单类似,jQuery 可以通过<script>标签包含在 MVC 视图中。 然而,在本例中,让我们看看为此目的使用绑定的情况。
绑定可以帮助减少浏览器发出的 HTTP 请求的数量。 它允许样式表、JavaScript 或其他文件组合在一个称为 bundle 的单一文件中。 这个合并的文件可以使用单个 HTTP 请求作为一个单元下载。
准备
-
Launch a new ASP.NET Web Application project in Visual Studio using the Empty template. Ensure that the MVC checkbox is checked, as shown in the following screenshot:
![Getting ready]()
-
This will create a project with MVC folders. Right-click on the Controllers folder in the Solution Explorer tab, and go to Add | Controller... as shown in the following screenshot:
![Getting ready]()
-
This will launch the Add Scaffold dialog box. Select MVC 5 Controller – Empty, and click on the Add button:
![Getting ready]()
-
On being prompted to add a name for the controller, type
HomeControllerand click on the Add button:![Getting ready]()
-
Next, open the HomeController in the source mode, and right-click on the
Indexaction method, as shown in the following screenshot. Click on Add View... as shown in the following screenshot:![Getting ready]()
-
This will launch the Add View dialog box. From the Template field, select Empty (without model). Uncheck the Use a layout page option and click the Add button to continue:
![Getting ready]()
注意事项
在其余的菜谱中,当被要求创建 MVC 应用时,按照前面提到的步骤 1 到 6 进行操作。
-
To use bundling, we need to install the ASP.NET Web Optimization package. This can be done from NuGet. From the
Filemenu, launch NuGet by navigating to Project | Manage NuGet Packages. Select Microsoft.AspNet.Web.Optimization from the list of available packages. If the package is not visible, search forweb.optimization, as shown in the following screenshot. Click on the Install button to download and install the latest version:![Getting ready]()
-
最后,在项目中创建一个
Scripts文件夹,并在该文件夹中包含 jQuery 库文件。
怎么做……
遵循以下步骤将 jQuery 绑定到 ASP 中.NET MVC:
-
在 MVC 项目的
App_Start文件夹中打开BundleConfig类。 如果文件不存在,在App_Start文件夹中新建module(VB)/class(c#),并将其命名为BundleConfig.vb/BundleConfig.cs。 -
In
BundleConfig.vb/BundleConfig.cs, add a namespace toSystem.Web.Optimizationat the top of the file:对于 VB,代码如下:
Imports System.Web.Optimization对于 c#,代码如下:
using System.Web.Optimization; -
Register and configure a bundle for jQuery in the
RegisterBundlesmethod inBundleConfigas follows:对于 VB,代码如下:
Public Module BundleConfig Public Sub RegisterBundles(ByVal bundles As BundleCollection) bundles.Add(New ScriptBundle("~/Scripts/jquery").Include( "~/Scripts/jquery-{version}.js")) End Sub End Module对于 c#,代码如下:
public class BundleConfig { public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/Scripts/jquery").Include( "~/Scripts/jquery-{version}.js")); } } -
To enable bundling in the development mode (optional), add the following code to the
RegisterBundlesmethod:对于 VB,代码如下:
BundleTable.EnableOptimizations = True对于 c#,代码如下:
BundleTable.EnableOptimizations = true; -
In the
Global.asax file, include the namespace forSystem.Web.Optimization, as shown in step 2 mentioned previously. Then, register the bundle in theApplication_Startmethod as follows:对于 VB,代码如下:
BundleConfig.RegisterBundles(BundleTable.Bundles)对于 c#,代码如下:
BundleConfig.RegisterBundles(BundleTable.Bundles); -
Now, open the Index view and include the namespace for
System.Web.Optimization, as shown in the following code:对于 VB,代码如下:
@Imports System.Web.Optimization对于 c#,代码如下:
@using System.Web.Optimization -
接下来,在
<head>元素中将 jQuery 脚本引用添加到视图中,如下所示:
注意事项
在调试模式下,通过将web.config文件中的<compilation>元素中的debug属性设置为true来禁用绑定。 要在调试模式中覆盖此设置并启用绑定,请在RegisterBundles方法中将BundleTable类的EnableOptimizations属性设置为true。
除非EnableOptimizations被设置为true,或者debug属性被设置为false,否则文件将不会被绑定,并且将使用文件的调试版本而不是最小化版本。
How it works…
jQuery 在 ASP 中绑定.NET MVC 可以通过以下步骤完成:
-
用于捆绑 jQuery
~/Scripts/jquery-{version}.js的通配符字符串包括开发和缩小版。 智能感知使用的.vsdoc文件不包含在包中。 -
打开调试模式时,使用对应的调试版本。 在发布模式中,最小化的版本捆绑在一起。
-
On running the view in a browser, the bundled file can be seen on viewing the source in the browser window, as shown in the following HTML markup:
![How it works…]()
参见 also
使用**一个 CDN 在 MVC中加载 jQuery
使用 CDN 在 MVC 中加载 jQuery
由于在 web 应用中使用 CDN 的优势,bundle 也支持从 CDN 中直接加载文件。 本菜谱将解释如何将 MVC 项目配置为使用 CDN。
准备
这个配方是前一个配方的的延续,在 ASP 中捆绑 jQuery.NET MVC。 因此,遵循前面食谱中描述的所有步骤。
怎么做……
下面是在 MVC 中加载 jQuery 的步骤:
-
在
BundleConfig模块/类中,修改RegisterBundles方法以将UseCdn属性设置为true,如步骤 2 中的代码片段所示。 -
Declare the required CDN path, and add a
ScriptBundlewith two parameters: the virtual path of the bundle and the CDN path, as follows:对于 VB,代码如下:
Public Module BundleConfig Public Sub RegisterBundles(ByVal bundles As BundleCollection) bundles.UseCdn = True Dim cdnPath As String = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.4.min.js" bundles.Add(New ScriptBundle("~/Scripts/jquery", cdnPath).Include("~/Scripts/jquery-{version}.js")) End Sub End Module对于 c#,代码如下:
public class BundleConfig { public static void RegisterBundles(BundleCollection bundles) { bundles.UseCdn = true; string cdnPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.4.min.js"; bundles.Add(new ScriptBundle("~/Scripts/jquery", cdnPath).Include("~/Scripts/jquery-{version}.js")); } }
How it works…
下面是使用 CDN 在 MVC 中加载 jQuery 的步骤:
-
通过设置
UseCdn属性,可以从 CDN 服务绑定脚本。 -
在开发模式下,应用从本地Scripts文件夹中检索文件。 发布模式下,使用 CDN 路径为捆绑的脚本提供服务。
-
但是,也有可能 CDN 出现故障。 因此,需要一个回退机制,以便在这种场景中本地提供脚本。 这可以通过在所需视图中添加以下
<script>块来实现:@Scripts.Render("~/Scripts/jquery") <script type="text/javascript"> if (typeof jQuery == 'undefined') { var e = document.createElement('script'); e.src = '@Url.Content("~/Scripts/jquery-2.4.1.js")'; e.type = 'text/javascript'; document.getElementsByTagName("head")[0].appendChild(e); } </script>
参见 also
Hello World 在 ASP 中的应用。 asp.net MVC 使用 jQuery配方
Hello World 使用 jQuery 实现 asp.net MVC
这个配方演示了如何编写一个简单的 jQuery 代码来在 ASP 中显示 Hello World。 净 MVC 项目。
准备
使用在中创建的MyMvcApplication项目在 ASP 中绑定 jQuery.NET MVC配方。
怎么做……
下面是编写简单 jQuery 代码的步骤:
- 打开 Index 视图,并将以下标记添加到
<body>元素: - 在
<head>元素中,包含以下 jQuery 代码: - 右键单击 Index 视图,并选择view in Browser (Internet Explorer)。
How it works…
下面是用 ASP 打印 Hello World 的步骤。 使用 jQuery 的 asp.net MVC:
-
符号用于实例化
jQuery对象。 -
当 DOM 准备好时,触发
.ready()函数。 它通常用于在页面上执行所需的 jQuery 代码。 -
带有
id = "divMessage",的 HTML<div>元素用于显示 Hello World 消息,可以使用 jQuery 的#identifier选择器来访问它的 ID——也就是说,使用#divMessage选择器。 -
Using the
.css()property of thejQueryobject, the font style, size, and text of the<div>element are manipulated so that the following output is displayed on running the application:![How it works…]()
参见 also
bundle NET MVC配方
调试 Visual Studio 中的 jQuery 代码
调试对于在开发阶段解决代码中的 bug 是不可避免的。 有时,bug 也会滑入生产中。 Visual Studio 支持开发人员以与服务器端代码相同的方式调试 JavaScript 代码。 但是 Visual Studio 中存在一定的局限性,目前只能在 Internet Explorer 浏览器中进行调试。
准备
-
To enable debugging for a particular project, both the project properties and
web.configmust be updated. To update the project properties, right-click on the project in the Solution Explorer tab, and select Properties. Go to the Web tab, and select the ASP.NET checkbox in the Debuggers section, as shown in the following screenshot:![Getting ready]()
-
在
web.config文件中,转到configuration/system.web/compilation元素。 如果元素不存在,添加一个新节点。 要开启调试,应该将<compilation>节点的debug属性设置为true,如下所示:
怎么做……
在 Visual Studio 中调试 jQuery 代码可以通过以下步骤完成:
-
The first step in debugging is to define breakpoints in the JavaScript code, where the execution will be halted so that variables, program flow, and so on can be inspected. To define breakpoints, just click on the left-hand side gray margin in the source code. Each breakpoint is represented by a small red circle, as shown in the following figure:
![How to do it…]()
-
Press F5, or navigate to Debug | Start Debugging, to start running the application in the debug mode. The execution will stop at the first breakpoint that it comes across, as shown in the following screenshot:
![How to do it…]()
-
要在运行时启动 Watch 窗口以观察变量的值,请转到Debug|Windows|Watch。 这将显示窗口,如前面截图中所示的。
-
You will also be able to see a window showing the breakpoints by navigating to Debug | Windows | Breakpoints. The result is shown in the following screenshot:
![How to do it…]()
-
要逐行跟踪代码,按F11或在每行导航到Debug|Step Into。 要跳转到下一个断点,按F5。
-
按Shift+F5停止调试。
注意事项
确保在生产环境中启动应用之前关闭调试。 启用了调试的应用的性能较慢,因为调试会生成额外的信息,使调试器能够显示变量的内容。 它还向调用堆栈输出更多信息,这可能成为生产环境中的安全问题。
参见 also
在 web 项目中使用 jQuery 的Hello World
二、使用 jQuery 选择器与 ASP.NET 控制器
本章将向你介绍各种类型的选择器,它们可以用于 ASP.NET 控制。 本章将介绍以下食谱:
- 选择使用 ID 的控件并显示其值
- 选择一个使用 CSS 类的控件
- 选择使用 HTML 标记的控件
- 根据控件的属性选择控件
- 根据元素在 DOM 中的位置选择元素
- 启用/禁用 web 表单上的控件
- 在 MVC 应用中使用选择器
注意事项
本书提供的源代码将每个菜谱作为一个独立的项目编写,并命名为Recipe1、Recipe2、Recipe3,等等。
简介
一个网页是由各种 HTML 元素组成的,如表单、div、span、段落、超链接、表格、输入、选择等。 在编写客户机脚本时,通常需要操作这些元素。 在 JavaScript 中,可以通过document.getElementById()语句使用这些元素的唯一 id 访问它们。
但是,在实际的应用中,可能需要基于属性而不是 id 来检索元素。 或者一些应用可能需要检索和操作多个元素。 这是通过使用 jQuery 中的选择器实现的。
选择器是一个 jQuery 构造,它根据指定的条件来检索页面上的元素。 它可以用来返回单个或多个元素。 使用 jQuery 选择器,它可以匹配元素使用他们的ID,CSS 类,标签名称【显示】和位置的文档对象模型(DOM)或其他属性。****
**当一个 ASP。 在浏览器中查看。NET 页面时,控件呈现为 HTML 元素。 这使得选择 ASP 成为可能.NET 控件使用标准 jQuery 选择器。 下表总结了一些常见的 ASP。 . NET 控件到其呈现的 HTML 对等物:
|ASP.NET 控制
|
呈现的 HTML 元素
|
呈现的 HTML 标记
|
| --- | --- | --- |
| BulletedList | ul,他们 | <ul><li></li>``<li></li></ul> |
| 按钮 | 输入 | <input type= "submit"/> |
| 复选框 | 输入 | <input type= "checkbox"/> |
| CheckBoxList | 输入 | <input type= "checkbox" name="CheckBoxList1"/>``<input type= "checkbox" name="CheckBoxList1"/> |
| DropDownList | 选择,选项 | <select><option></option>``<option></option></select> |
| 超链接 | 一个 | <a> |
| 图像 | img | <img> |
| ImageButton | 输入 | <input type= "image"/> |
| 标签 | 跨度 | <span> |
| LinkButton | 一个 | <a> |
| 列表框 | 选择,选项 | <select><option></option>``<option></option></select> |
| 面板 | div | <div> |
| RadioButton | 输入 | <input type= "radio"/> |
| RadioButtonList | 输入 | <input type= "radio" name="RadioButtonList1"/>``<input type= "radio" name="RadioButtonList1"/> |
| 文本框 | 输入 | <input type="text"> |
| 显示数据表格 | 表格 | <table> |
标准 jQuery 选择器也可以和 ASP 一起使用。 因为 MVC 应用使用原始 HTML 标记或 HTML 类的内置扩展方法来呈现内容。
jQuery 选择器可以大致分为以下几种类型:
-
: These selectors are similar to CSS selectors that are used in style sheets to apply styles to selected elements. Basic selectors can be used to retrieve elements based on the HTML tag, CSS class, element ID, or a combination of all these. The examples of basic selectors are as follows:
|Example
|
Description
|
|$("*")| This will select all elements on the page |
|$("div")| This will select all the<div>elements on the page |
|$(".highlight")| This will use CSS classhighlightto select all elements on the page. |
|$("#footer")| This will select the element whose ID is equal tofooter|
|$("div, p, .highlight, #footer")| This will select all<div>and<p>elements, all CSShighlightelements, And the element whose ID is T11. | -
Hierarchy selectors : These selectors are also similar to CSS selectors and are used to select child elements in the DOM tree. The examples of hierarchy selectors are listed as follows: that are direct children of the
|<div>element. that follow<div>and have the same parent element as<div>elements. adjacent to<div>elements.Example
|
Description
|
| --- | --- |
|$("div p")| This will select all the<p>elements in the<div>element |
|$("#footer p")| This will select all descendants of the element whose ID is equal to footer. |
|$("div > p")| This selects all the<p>elements |
|$("div ~ p")| This will select all<p>elements |
|$("div + p")| This will select all<p>elements | -
Attribute selectors : These selectors retrieve elements based on the attributes they have. The examples of attribute selectors are listed as follows: .
|Example
|
Description
|
| --- | --- |
|$("a[href]")| This will select all the<a>elements with thehrefattribute |
|$("a[href= 'http://www.google.com']")| This will select all<a>elementsthathrefare exactly equal to'http://www.google.com'. |
|$("a[href*= 'google.com']")| This will select all<a>elements thathrefcontain'google.com'. |
|$("a[href^= 'https']")| This will select all the<a>elements whosehrefbegins with'https'. |
|$("a[href$= '.org']")| This will select all<a>elements ending inhref. |
|$("a[hreflang|= 'en']")| This will selecthreflangequal to'en'or all<a>beginning with'en-'. Elements. | -
: These selectors are used to work with various form elements, such as an
input,checkbox,radio, and so on. The examples of form selectors are as follows:$(":selected")
|$(":enabled")Example
|
Description
|
|$(":button"), $(":submit"), $(":reset"), $(":text"), $(":radio"), $(":checkbox"), $(":password"), $(":image"), $(":file")| This will select a specific type ofinputelement |
|$(":input")| This will select allformelements |
|$(":checked")| This will select all selected check boxes and radio buttons |
| This will return all selected<option>elements |
| This will return all enabledformelements |
|$(":disabled")| this will return all disabled elementsformElement | -
Position filters : These selectors retrieve elements based on their position in a collection. The examples of position selectors are listed as follows:
|Example
|
Description
|
|$(".highlight :first")| This selects the first element of the CSS classhighlight. |
|$(".highlight :last")| This select the last element of CSS classhighlight|
|$(".highlight :odd")| It selects an odd number of elements from all elements of the CSS classhighlight. When the index is zero, It selects even elements from all elements of CSS classhighlight. When the index is zero, Select element |
|$(".highlight :lt(3)")| from all elements of CSS classhighlightwith index 3. It selects elements with an index less than 3 from all elements of the CSS classhighlight|
|$(".highlight :gt(3)")| When index is zero, select the element with index greater than 3 from all elements of CSS class |
注意事项
在http://api.jquery.com/category/selectors可以找到更多关于不同类型的 jQuery 选择器的信息。
在编写 jQuery 代码时,经常使用匿名函数。 匿名函数是一个没有命名标识符的函数。 它通常用作其他函数的参数。
假设我们有一个onDocumentReady()函数。 这个函数作为参数传递给$(document).ready()函数,如下所示:
function onDocumentReady(){…}
$(document).ready(onDocumentReady);
匿名函数可以作为参数直接传递给$(document).ready(),如下所示:
$(document).ready(function(){ …} );
但是,请注意,匿名函数一旦创建就不能访问。
使用 ID 选择控件并显示其值
这个配方演示了如何访问基本的 ASP.NET 控件,例如CheckBoxList,TextBox和RadioButtonList,使用 jQuery 的#identifier选择器。 本例中使用的结构如下:
构造
|
类型
|
描述
|
| --- | --- | --- |
| $(#identifier) | jQuery 选择器 | 此基于其ID选择元素 |
| $(this) | jQuery 对象 | 它引用当前 jQuery 对象 |
| :checked | jQuery 选择器 | 这将选择选中的输入元素 |
| .click() | jQuery 事件绑定 | 这将处理程序绑定到元素的click事件 |
| .each() | jQuery 方法 | 这将遍历匹配的元素,并为每个元素执行一个函数 |
| .find() | jQuery 方法 | 这将查找与筛选器匹配的所有元素 |
| .html() | jQuery 方法 | 这将返回第一个匹配元素的 HTML 内容,或者设置每个匹配元素的 HTML 内容 |
| .is() | jQuery 方法 | 如果匹配的元素满足给定条件,则返回一个布尔值 |
| .next() | jQuery 方法 | 这将获取元素的直接兄弟元素 |
| :selected | jQuery 选择器 | 这将检索选定的输入元素 |
| .text() | jQuery 方法 | 这将返回每个匹配元素的组合文本内容,或者设置每个匹配元素的文本内容 |
| .val() | jQuery 方法 | 返回第一个匹配元素的值,或者设置每个匹配元素的值 |
准备
下面是使用基本 ASP 创建表单的步骤.NET 控件:
-
In this example, we will create a simple User Registration form, as shown in the following screenshot:
![Getting ready]()
-
创建一个ASP.NET Web 应用项目使用空模板和名称项目
Recipe1(或任何其他合适的名称)。 -
添加一个Web 窗体到项目中,并添加名称其
Default.aspx。 -
创建一个
Scripts文件夹,并添加 jQuery 文件(库的调试和发布版本)。 -
使用
<script>块或ScriptManager控件将 jQuery 库包含在窗体中,如第一章,中所述。 。 -
现在,拖放 ASP。 . NET 控件通过导航到工具箱|Standard控件来创建窗体,如上图所示。
-
表单的 HTML 标记如下:
<table> <tr> <td> <asp:Label ID="lblName" runat="server" Text="Name"></asp:Label> </td> <td> <asp:TextBox ID="txtName" runat="server" Width="223px"></asp:TextBox> </td> </tr> <tr> <td> <asp:Label ID="lblGender" runat="server" Text="Gender"></asp:Label> </td> <td> <asp:RadioButtonList ID="rblGender" runat="server"> <asp:ListItem Text="Male" Value="Male"></asp:ListItem> <asp:ListItem Text="Female" Value="Female"></asp:ListItem> </asp:RadioButtonList> </td> </tr> <tr> <td> <asp:Label ID="lblEducation" runat="server" Text="Highest Education"></asp:Label> </td> <td> <asp:DropDownList ID="ddlEducation" runat="server" Height="16px" Width="231px"> <asp:ListItem Text="--Select--" Value=""></asp:ListItem> <asp:ListItem Text="Post Graduate" Value="PG"></asp:ListItem> <asp:ListItem Text="Degree" Value="DG"></asp:ListItem> <asp:ListItem Text="Diploma" Value="DP"></asp:ListItem> <asp:ListItem Text="A-Levels" Value="AL"></asp:ListItem> <asp:ListItem Text="O-Levels" Value="OL"></asp:ListItem> </asp:DropDownList> </td> </tr> <tr> <td> <asp:Label ID="lblInterest" runat="server" Text="Interest Areas"></asp:Label> </td> <td> <asp:CheckBoxList ID="chkInterest" runat="server"> <asp:ListItem Text="ASP.NET" Value="ASP.NET"></asp:ListItem> <asp:ListItem Text="Java" Value="Java"></asp:ListItem> <asp:ListItem Text="Android" Value="Android"></asp:ListItem> <asp:ListItem Text="HTML5" Value="HTML5"></asp:ListItem> <asp:ListItem Text="XML" Value="XML"></asp:ListItem> </asp:CheckBoxList> </td> </tr> <tr> <td colspan="2"> <asp:CheckBox ID="chkSubscribe" runat="server" Text="Subscribe to newsletter" /> </td> </tr> <tr> <td> </td> <td> </td> </tr> <tr> <td> </td> <td> <asp:Button ID="btnSubmit" runat="server" Text="Submit" /> </td> </tr> </table>
怎么做……
在 jQuery 库被包含在<script>块中后,在中包含以下 jQuery 代码:
<script type="text/javascript">
$(document).ready(function() {
$("#<%=btnSubmit.ClientID%>").click(function() {
var strName = $("#<%=txtName.ClientID%>").val();
var strGender =
$("#<%=rblGender.ClientID%> input:checked").val();
var strEducation = $("#<%=ddlEducation.ClientID%>").find(":selected").text();
var strInterest = "";
$("#<%=chkInterest.ClientID%> input:checked").each(
function() {
strInterest += " " + $(this).val();
});
var strSubscribe = "";
if ($("#<%=chkSubscribe.ClientID%>").is(":checked")) {
strSubscribe = $("#<%=chkSubscribe.ClientID%>").next().html();
}
var strDisplayMsg = "You are about to submit the following data: \r\n\r\n" +
"Name: " + strName + "\r\n" +
"Gender: " + strGender + "\r\n" +
"Highest Education: " + strEducation + "\r\n" +
"Interest Areas: " + strInterest + "\r\n" +
strSubscribe + "\r\n\r\n" +
"Click OK to proceed"
window.confirm(strDisplayMsg);
});
});
</script>
注意事项
前面的<script>块可以包含在<head>或<form>元素中,这取决于 jQuery 库如何包含在页面中。
How it works…
让我们看看是如何工作的:
-
Save the application using Ctrl + S, and run it by pressing F5. This will launch the User Registration page. Enter some test values in the controls, and click on the Submit button. A confirmation prompt is displayed that summarizes the values of the controls as follows:
![How it works…]()
注意事项
请注意,没有对控件进行验证,并且该页面还允许您提交空白表单。 验证将在后续章节中描述。
-
In the jQuery
<script>block, every ASP.NET control is retrieved using the#identifierselector on the equivalent rendered HTML tag. The code is executed when theclickevent of theSubmitbutton is raised, as shown in the following code:$("#<%=btnSubmit.ClientID%>").click(function () {…});注意事项
ClientID为 ASP 分配的值.NET 到服务器控件在运行时生成的等效 HTML 标记的ID中。 ASP.NET 为生成客户端提供了各种算法,如 AutoID、Static、Predictable 和 Inherit。 -
在运行时,
TextBox控件呈现为以下 HTMLinput元素(右键单击浏览器中的页面,并单击View Source以查看呈现的 HTML): -
因此,在 jQuery 代码中,
TextBox控件的值带有ID等于txtName可以通过以下代码访问:var strName = $("#<%=txtName.ClientID%>").val(); -
The
RadioButtonListcontrol is rendered as the following HTML code:<table id="rblGender"> <tr> <td><input id="rblGender_0" type="radio" name="rblGender" value="Male" /><label for="rblGender_0">Male</label></td> </tr> <tr> <td><input id="rblGender_1" type="radio" name="rblGender" value="Female" /><label for="rblGender_1">Female</label></td> </tr> </table>在 jQuery 代码中,可以使用选中的过滤器访问列表中选中的单选按钮,如下所示:
var strGender = $("#<%=rblGender.ClientID%> input:checked").val(); -
The
DropDownListcontrol is rendered as the following HTML code:<select name="ddlEducation" id="ddlEducation" style="height:16px;width:231px;"> <option value="">--Select--</option> <option value="PG">Post Graduate</option> <option value="DG">Degree</option> <option value="DP">Diploma</option> <option value="AL">A-Levels</option> <option value="OL">O-Levels</option> </select>jQuery 代码使用
selected过滤器从DropDownList控件中找到选中的项目,并返回其text值,如下所示:var strEducation = $("#<%=ddlEducation.ClientID%>").find(":selected").text(); -
The
CheckBoxListcontrol is rendered as the following HTML code:<table id="chkInterest"> <tr> <td><input id="chkInterest_0" type="checkbox" name="chkInterest$0" value="ASP.NET" /><label for="chkInterest_0">ASP.NET</label></td> </tr> <tr> <td><input id="chkInterest_1" type="checkbox" name="chkInterest$1" value="Java" /><label for="chkInterest_1">Java</label></td> </tr> <tr> <td><input id="chkInterest_2" type="checkbox" name="chkInterest$2" value="Android" /><label for="chkInterest_2">Android</label></td> </tr> <tr> <td><input id="chkInterest_3" type="checkbox" name="chkInterest$3" value="HTML5" /><label for="chkInterest_3">HTML5</label></td> </tr> <tr> <td><input id="chkInterest_4" type="checkbox" name="chkInterest$4" value="XML" /><label for="chkInterest_4">XML</label></td> </tr> <table>jQuery 代码使用
.each()方法循环遍历每个checked元素,并将其值附加到strInterest字符串中,如下所示:var strInterest = ""; $("#<%=chkInterest.ClientID%> input:checked").each(function () { strInterest += " " + $(this).val(); }); -
The subscribe
CheckBoxcontrol renders two sibling HTML tags:<input>and<label>, as follows:<input id="chkSubscribe" type="checkbox" name="chkSubscribe" /><label for="chkSubscribe">Subscribe to newsletter</label>因此,jQuery 代码使用
.next().html()来确定CheckBox控件的文本值,如下所示:var strSubscribe = ""; if ($("#<%=chkSubscribe.ClientID%>").is(":checked")) { strSubscribe = $("#<%=chkSubscribe.ClientID%>").next().html(); }如果复选框未选中,
strSubscribe为空字符串。 -
最后,将控件检索到的所有值附加到
strDisplayMsg字符串,脚本使用 JavaScript 的window.confirm()命令向用户显示确认对话框。 如果用户单击OK,表单就会被提交。 点击取消将阻止表单提交:var strDisplayMsg = "You are about to submit the following data: \r\n\r\n" + "Name: " + strName + "\r\n" + "Gender: " + strGender + "\r\n" + "Highest Education: " + strEducation + "\r\n" + "Interest Areas: " + strInterest + "\r\n" + strSubscribe + "\r\n\r\n" + "Click OK to proceed" window.confirm(strDisplayMsg);
参见 also
- 使用 CSS 类配方选择控件
选择一个使用 CSS 类的控件
本食谱将演示如何访问 ASP.NET 控件,如Image、Panel和BulletedList,基于分配给它们的CSSClass。 本例中使用的结构如下:
构造
|
类型
|
描述
|
| --- | --- | --- |
| $(".class") | jQuery 选择器 | 它匹配指定 CSS 类的所有元素。 |
| .attr("name") OR``.attr("name", "value") | jQuery 方法 | 这将返回一个字符串,其中包含第一个匹配元素所需的属性值。 它还可以用于将属性设置为所需的值。 |
| .click() | jQuery 事件绑定 | 这将处理程序绑定到元素的click事件。 |
| event.preventDefault() | jQuery 方法 | 这将防止触发事件的默认动作。 |
| .hide() | jQuery 方法 | 这将隐藏匹配的元素。 |
| .is() | jQuery 方法 | 如果匹配的元素满足给定条件,则返回一个布尔值。 |
| .next() | jQuery 方法 | 这将获取元素的直接兄弟元素。 |
| .show() | jQuery 方法 | 这会显示匹配的元素。 |
| .toggle() | jQuery 方法 | 显示或隐藏匹配的元素。 |
准备
让我们通过访问 ASP.NET 控件使用CssClass:
-
To demonstrate the CSS selector in jQuery, we will build a simple application that displays a List of Questions. The answers can be seen by clicking on the respective plus + icon next to the question:
![Getting ready]()
页的顶部也有一个复选框。 点击此复选框,将显示所有的答案,如下图所示:
![Getting ready]()
-
通过点击负-图标,相应的答案可以折叠。
-
首先,创建一个ASP.NET Web 应用项目使用空模板,且名称项目
Recipe2(或任何其他合适的名称)。 -
添加一个Web 窗体到项目中,并添加名称其
Default.aspx。 -
创建一个
Scripts文件夹,并添加 jQuery 文件(库的调试和发布版本)。 -
使用
<script>块或ScriptManager控件将 jQuery 库包含在窗体中,如第一章,中所述。 。 -
在项目中创建一个
images文件夹,并包含加号和减号图标的图像。 -
现在,拖放 ASP。 . NET 控件通过导航到工具箱|Standard控件来创建所需的表单,如上图所示。
-
表单的 HTML 标记如下:
-
添加以下 CSS 样式到页面:
怎么做……
在引用 jQuery 库之后创建一个<script>块,并添加以下代码:
<script type="text/javascript">
$(document).ready(function() {
$(".answer").hide();
$("#<%=chkShowAll.ClientID%>").click(function() {
if ($("#<%=chkShowAll.ClientID%>").is(":checked")) {
$(".answer").show();
$(".image").attr("src", "images/minus.png");
} else {
$(".answer").hide();
$(".image").attr("src", "images/plus.png");
}
});
$(".image").click(function(evt) {
$(this).next(".answer").toggle();
var src = ($(this).attr("src") === "images/plus.png") ? "images/minus.png" : "images/plus.png";
$(this).("src", src);
evt.preventDefault();
});
});
</script>
How it works…
使用CssClass选择 ASP.NET 控件可以在以下步骤中完成:
-
On running the application by pressing F5, all page elements with the
answerCssClass are hidden by executing the following statement:$(".answer").hide();注意事项
注意:因此,一旦页面加载,只有问题是可见的。
-
当您单击页面顶部的复选框时,它的
click事件将被触发。 事件处理程序绑定到click事件,如下所示: -
In the preceding
clickevent handler, firstly, the status of the checkbox is determined using thecheckedfilter. If the checkbox is checked, then the answers are shown and the plus icons are changed to minus icons:if ($("#<%=chkShowAll.ClientID%>").is(":checked")) { $(".answer").show(); $(".image").attr("src", "images/minus.png"); }如果复选框未选中,答案将被隐藏,减号图标将更新为加号图标:
else { $(".answer").hide(); $(".image").attr("src", "images/plus.png"); }因此,在
answer和image元素上使用 CSS 选择器,可以显示或隐藏所需的内容。 -
In addition to this, the user can click on the plus and minus icons to expand or collapse the answers, respectively. Hence, a
clickevent is tied to theimageelements using the CSS selector for the images, as follows:$(".image").click(function (evt) {…});在前面的事件处理程序中,图像后面的
answer元素被切换为显示或隐藏,如下所示:$(this).next(".answer").toggle();最后,图像也被切换——即,使用
.attr()方法,从加减或从减到加:var src = ($(this).attr("src") === "images/plus.png") ? "images/minus.png" : "images/plus.png"; $(this).attr("src", src);最后,为了防止图像
click事件提交表单,执行evt.preventDefault()。
参见 also
- 根据元素在 DOM 配方中的位置选择元素
选择一个使用 HTML 标记的控件
这个配方演示了如何访问 ASP.NET 控件使用在运行时生成的相应 HTML 标记。 我们将演示如何使用生成tableHTML 标记的GridView控件。 GridView的每一行呈现trHTML 标记。 这个示例使用了以下结构:
构造
|
类型
|
描述
|
| --- | --- | --- |
| $("html_tag") | jQuery 选择器 | 这将选择具有指定 HTML 标记的所有元素 |
| $(this) | jQuery 对象 | 它引用当前 jQuery 对象 |
| .addClass() | jQuery 方法 | 这会将指定的 CSS 类添加到每个匹配的元素中 |
| [attribute$="value"] | jQuery 选择器 | 这将选择具有指定属性的元素,以字符串"value"结尾 |
| :checkbox | jQuery 选择器 | 这只从匹配的元素中选择复选框元素 |
| .click() | jQuery 事件绑定 | 这将处理程序绑定到元素的click事件 |
| .find() | jQuery 方法 | 这将查找匹配筛选器的所有元素 |
| .is() | jQuery 方法 | 如果匹配的元素满足给定条件,则返回一个布尔值 |
| .parents() | jQuery 方法 | 这将选择 DOM 树中匹配元素的祖先 |
| .removeClass() | jQuery 方法 | 这将从每个匹配的元素中删除指定的 CSS 类 |
准备
让我们选择 ASP.NET 控件使用 HTML 标记:
-
In this example, we will create a web page to display a List of Suppliers from the Northwind database in a
GridViewcontrol, as shown in the following screenshot:![Getting ready]()
-
Each row in the
GridViewhas aCheckBoxcontrol in the first column. By selecting the checkbox, the respective row is highlighted, as shown in the following screenshot:![Getting ready]()
注意事项
同样地,通过取消选中复选框,高亮显示将被删除。
-
要开始,创建一个ASP.NET Web 应用项目使用空模板,名称项目
Recipe3(或任何其他合适的名称)。 -
添加一个Web 窗体到项目中,并添加名称其
Default.aspx。 -
创建一个
Scripts文件夹,并添加 jQuery 文件(库的调试和发布版本)。 -
使用
<script>块或ScriptManager控件将 jQuery 库包含在窗体中,如第一章,中所述。 。 -
在Design模式中打开
Default.aspx,通过导航到Toolbox|Data,拖放GridView控件。 -
Populate the gridview with the Suppliers data from the Northwind database using LINQ by following Steps 9 to 15. If you are familiar with using LINQ, proceed to Step 16 to add the checkbox field and required columns to the gridview markup.
提示
安装北风数据库
Northwind 是一个开源数据库,可以从https://northwinddatabase.codeplex.com下载。
阅读更多关于:如何从 MSDN 页面安装示例数据库:https://msdn.microsoft.com/en-us/library/8b6y4c7s.aspx。
-
将App_Code文件夹添加到项目中,右键单击项目,并导航到Add|Add ASP。 |App_Code。
-
Right-click on the App_Code folder, and go to Add | Add New Item. From the dialog box, select LINQ to SQL Classes, and name the file
Northwind.dbml, as shown in the following screenshot. Click on the Add button to proceed:

- Open
Northwind.dbmlin the designer. Connect to the Northwind database, running on MS SQL Server using Server Explorer. Drag and drop the Suppliers table onto the designer, as shown in the following screenshot:

- Now, open the
Default.aspxweb form in the Design mode, and click on the GridView control. A small arrow icon appears in the top-right corner of the GridView control, and when you click on it, the GridView Tasks submenu opens up, as shown in the following screenshot:

- In the GridView Tasks submenu, go to Choose Data Source | <New data source…>. From the Data Source Configuration Wizard, select LINQ, and click on OK.

- This will launch the Configure Data Source dialog box. From the drop-down menu, select the Recipe3.App_Code.NorthwindDataContext option, and click on Next.

### 提示
注意,如果下拉菜单中没有出现**NorthwindDataContext**,则将`System.Data.Linq`添加到`web.config`中的`system.web/compilation/assemblies`元素中,如下所示:
```
<system.web>
<compilation debug="true">
<assemblies>
<add assembly="System.Data.Linq, Version=4.0.30319.17929, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</assemblies>
</compilation>
</system.web>
```
- Check the columns from the Suppliers table that need to be displayed in the
GridView, or select ***** to retrieve all columns, and click on Finish:

- 在Source模式中打开
Default.aspx,按照的方法更新网格视图的标记,在第一列中添加CheckBox控件作为TemplateField。 我们还将将显示限制为几个重要的列。 另外,将GridView中的ID改为gvSupplierList:
```
<asp:GridView ID="gvSupplierList" runat="server" AutoGenerateColumns="False" DataKeyNames="SupplierID" DataSourceID="LinqDataSource1">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="SupplierID" HeaderText="SupplierID" InsertVisible="False" ReadOnly="True" SortExpression="SupplierID" />
<asp:BoundField DataField="CompanyName" HeaderText="CompanyName" SortExpression="CompanyName" />
<asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />
<asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
<asp:BoundField DataField="Region" HeaderText="Region" SortExpression="Region" />
<asp:BoundField DataField="PostalCode" HeaderText="PostalCode" SortExpression="PostalCode" />
<asp:BoundField DataField="Country" HeaderText="Country" SortExpression="Country" />
</Columns>
</asp:GridView>
```
- To enable paging and sorting on the GridView (optional), from the GridView Tasks submenu, check the Enable Paging and Enable Sorting options as shown in the following screenshot:

- 在 web 表单的
<head>元素中添加以下<style>:
```
<style>
.highlight{
background-color:darkgrey;
}
</style>
```
由于我们使用的是集成安全,windows 帐户应该被授予访问 Northwind 数据库的权限,如下步骤所示:
-
In the SQL Server Object Explorer dialog box, go to Databases | Northwind | Security | Users. Right-click on Users and click on New User, as shown in the following screenshot:
![Getting ready]()
-
This will launch the User-New dialog box. From the drop-down menu, change User type to Windows user. Go the User name option, and select the windows account that you have used to log in to the system, as shown in the following screenshot:
![Getting ready]()
-
In the same dialog box, in the left-hand side panel, click on the Owned Schemas tab. Check db_owner, as shown in the following screenshot:
![Getting ready]()
-
Next, in the left-hand side panel, click on the Membership tab. Check db_owner, as shown in the following screenshot:
![Getting ready]()
-
点击OK保存。
怎么做……
在页面中包含 jQuery 库后,将以下 jQuery 代码添加到<script>块中:
<script type="text/javascript">
$(document).ready(function() {
$("table[id$=<%=gvSupplierList.ClientID%>").find("input:checkbox").click(
function() {
if ($(this).is(":checked"))
$(this).parents("tr").addClass("highlight");
else
$(this).parents("tr").removeClass("highlight");
});
});
</script>
How it works…
选择 ASP。 使用 HTML 标记的 NET 控件可以通过以下步骤完成:
-
In this example, the gridview is selected using the
<table>HTML tag that it generates at runtime. Each row of theGridViewcontrol is rendered as atrHTML tag. This can be seen by viewing the source at runtime:![How it works…]()
-
由于页面上可能有多个
<table>元素,所以使用id过滤表元素。 一旦选择了所需的<table>元素(即GridView控件),就使用.find("input:checkbox")选择器匹配第一列中的CheckBox控件。click事件处理程序绑定到CheckBox控件,如下所示: -
在
click事件处理程序绑定到CheckBox元素之后,下一个任务是使用:checked选择器确定复选框是否被选中,如下所示:if ($(this).is(":checked")) -
如果选中了复选框,则使用
.parents("tr")选择器选择其父表行。 接下来,将highlightCSS 类绑定到这个表行,如下所示: -
但是,如果复选框未选中,则需要删除突出显示。 这可以在相应的表行上使用
.removeClass()方法完成,如下所示:
参见 also
- 选择一个使用 ID 的控件并显示其值 recipe
根据控件的属性选择控件
在这个配方中,我们将选择 ASP.NET 控件基于它们所具有的特定属性。 该演示使用了 ASP 的NavigateUrl属性.NET 超链接控件,该控件作为anchor标记的href属性呈现。 使用的结构总结如下:
构造
|
类型
|
描述
|
| --- | --- | --- |
| $("#identifier") | jQuery 选择器 | 这将基于其ID选择一个元素。 |
| .addClass() | jQuery 选择器 | 这会将指定的 CSS 类添加到每个匹配的元素中 |
| [attribute*="value"] | jQuery 选择器 | 这将选择一个具有指定属性的元素,该属性包含字符串"value" |
| .click() | jQuery 事件绑定 | 这将处理程序绑定到元素的click事件 |
| event.preventDefault() | jQuery 方法 | 这将防止触发事件的默认动作 |
| .focus() | jQuery 事件绑定 | 这将触发元素的focus事件,或者将事件处理程序绑定到focusJavaScript 事件 |
| .removeClass() | jQuery 方法 | 这个将从每个匹配的元素中删除指定的 CSS 类 |
| .toLowerCase() | JavaScript 函数 | 将字符串转换为小写字符 |
| .val() | jQuery 方法 | 返回第一个匹配元素的值,或者设置每个匹配元素的值 |
准备
让我们创建一个网页,在其中我们将检索使用其属性的控件:
-
Consider the web page in the following screenshot:
![Getting ready]()
-
The web page consists of a list of Hyperlink controls. The Search textbox on the top of the page allows you to search the URLs set in the
NavigateUrlproperty of theHyperlinkcontrols by a keyword. If a particular keyword is present in the URL link, the corresponding link is highlighted, as shown in the following screenshot:![Getting ready]()
-
If another keyword is searched, a new set of links matching the new search keyword are highlighted, as follows:
![Getting ready]()
-
首先,创建一个ASP.NET Web 应用项目使用空模板,且名称项目
Recipe4(或任何其他合适的名称)。 -
添加一个Web 窗体到项目中,并添加名称其
Default.aspx。 -
创建一个
Scripts文件夹,并添加 jQuery 文件(库的调试和发布版本)。 -
使用
<script>块或ScriptManager控件将 jQuery 库包含在窗体中,如第一章,中所述。 。 -
在Design模式中打开
Default.aspx,通过导航到工具箱|Standard中拖放所需的控件,创建带有以下标记的窗体: -
在页面的
<head>元素中,添加以下样式:
怎么做……
在包含 jQuery 库之后,在页面中以<script>块的形式包含以下 jQuery 代码:
<script type="text/javascript">
$(document).ready(function() {
$("table[id$=<%=gvSupplierList.ClientID%>").find("input:checkbox").click(
function() {
if ($(this).is(":checked"))
$(this).parents("tr").addClass("highlight");
else
$(this).parents("tr").removeClass("highlight");
});
});
</script>
How it works…
按属性选择控件的工作方式如下:
-
当页面启动时,搜索文本框通过调用其
focus事件来接收焦点,使用以下代码:$("#<%=txtKeyword.ClientID%>").focus(); -
同时,一个事件处理程序附加到Search按钮的
click事件:$("#<%=btnSearch.ClientID %>").click(function (evt) {…} -
事件处理程序从文本框中读取搜索的关键字并将其转换为小写字符串:
var strKeyword = $("#<%=txtKeyword.ClientID%>").val().toLowerCase(); -
在高亮显示匹配的
anchor标签之前,页面上所有anchor标签的 CSS 类使用$("a")选择器重置:$("a").removeClass("highlight"); -
A search by its attribute is done on all
anchortags using theirhrefattributes. If thehrefattribute contains the search keyword, the link is highlighted by attaching the respective CSS class:$('a[href*= "' + strKeyword + '"]').addClass("highlight");最后,由于按钮
click事件,evt.preventDefault()阻止页面提交。
参见 also
- 使用 HTML 标记选择控件
根据元素在 DOM 中的位置选择元素
这个配方演示了当您在 DOM 树中访问元素时,如何使用其相对于其父元素的位置。 我们将使用 ASP.NETListBox控件用于此目的。 本例中使用的结构如下:
构造
|
类型
|
描述
|
| --- | --- | --- |
| $("#id > *") | jQuery 选择器 | 这将选择具有指定 ID 的控件的所有后代元素。 |
| $("#id :first-child") | jQuery 选择器 | 这将选择具有指定 ID 的控件的第一个子元素。 |
| $("#id :last-child") | jQuery 选择器 | 这将选择具有指定 ID 的控件的最后一个子元素。 |
| $("#id :lt(i)") | jQuery 选择器 | 这将选择具有指定 ID 且索引小于i的控件的所有子元素。 注意,索引从 0 开始。 |
| $("#id :gt(i)") | jQuery 选择器 | 这将选择具有指定 ID 且索引大于i的控件的所有子元素。 注意,索引从 0 开始。 |
| $("#id :nth-child(i)") | jQuery 选择器 | 这个选择具有指定 ID 且索引为i的控件的子元素。 注意,第 n 个子节点的索引从 1 开始。 |
| $("#id :nth-child(even)") | jQuery 选择器 | 这将选择具有指定 ID 且具有偶数索引的控件的所有子元素。 |
| $("#id :nth-child(odd)") | jQuery 选择器 | 这将选择具有指定 ID 且索引为奇数的控件的所有子元素。 |
| .addClass() | jQuery 方法 | 这会将指定的 CSS 类添加到每个匹配的元素中。 |
| .click() | jQuery 事件绑定 | 这将处理程序绑定到元素的click事件。 |
| event.preventDefault() | jQuery 方法 | 这将防止触发事件的默认动作。 |
| .removeClass() | jQuery 方法 | 这将从每个匹配的元素中删除指定的 CSS 类。 |
| .val() | jQuery 方法 | 返回第一个匹配元素的值,或者设置每个匹配元素的值。 |
准备
让我们创建一个网页,根据元素的位置选择元素:
-
Consider the following web page that consists of a list box populated with data from the Suppliers table from the Northwind database, as follows:
![Getting ready]()
-
There is a dropdown list at the top of the page that allows you to select items in the list box, depending on their position in the DOM tree. The dropdown list has options to select the first, last, items less than or greater than a particular index, the nth item, as well as odd or even items, as shown in the following screenshot:
![Getting ready]()
注意事项
注意,我们将在这个配方中使用硬编码索引。 在实际的场景中,最好提供一个文本框或一个下拉列表,让用户能够输入或选择所需的索引。
-
To demonstrate the working of the form, consider the scenario in which Odd Items is selected from the dropdown list. In this case, only odd indexed items from the list box are highlighted, as shown here:
![Getting ready]()
-
首先,创建一个ASP.NET Web 应用项目使用空模板,且名称项目
Recipe5(或任何其他合适的名称)。 -
添加一个Web 窗体到项目中,并添加名称其
Default.aspx。 -
创建一个
Scripts文件夹,并添加 jQuery 文件(库的调试和发布版本)。 -
使用
<script>块或ScriptManager控件将 jQuery 库包含在窗体中,如第一章,中所述。 。 -
在Design模式下打开
Default.aspxweb 窗体,通过导航到工具箱|Standard,拖放ListBox控件。 -
按照步骤 10 到 18,使用 LINQ 使用来自 Northwind 数据库的供应商数据填充列表框。 如果您熟悉使用 LINQ,请继续步骤 19。
-
将App_Code文件夹添加到项目中,右键单击项目并导航到添加|添加 ASP。 |App_Code。
-
右键单击App_Code文件夹,然后转到Add|Add New Item。 在对话框中,选择LINQ to SQL Classes,并选择命名文件
Northwind.dbml。 -
Open
Northwind.dbmlin the designer. Connect to the Northwind database running on MS SQL Server using Server Explorer. Drag and drop the Suppliers table on the designer, as shown here:

- Now, open the
Default.aspxweb form in the Design mode, and click on the ListBox control. A small arrow icon appears in the top-right corner of the ListBox control, and when you click on it, the ListBox Tasks submenu opens up, as shown in the following screenshot:

- From the ListBox Tasks submenu, select Choose Data Source. This launches the Data Source Configuration Wizard, as shown in the following screenshot. Select <New data source…> from the first drop-down menu:

- This will prompt you to select Choose a Data Source Type. Select LINQ, and click on OK:

- On being prompted to select Choose a Context Object, choose Recipe5.App_Code.NorthwindDataContext from the drop-down menu, and click on Next:

### 提示
注意,如果下拉菜单中没有出现**NorthwindDataContext**,将`System.Data.Linq`添加到`web.config`中的`system.web/compilation/assemblies`元素,如下所示:
```
<system.web>
<compilation debug="true">
<assemblies>
<add assembly="System.Data.Linq, Version=4.0.30319.17929, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</assemblies>
</compilation>
</system.web>
```
- Check the SupplierID and CompanyName columns from the Suppliers table, and click on Finish:

- Set the display field of the list box to
CompanyNameand the value field toSupplierID, as shown in the following screenshot, and click on OK:

- 下面的代码是完成前面的步骤后页面的完整标记:
- 在页面的
<head>元素中,包含以下样式以突出显示所选的子项目:
怎么做……
将下面的 jQuery 代码添加到页面中包含库后的<script>块中:
<script type="text/javascript">
$(document).ready(function() {
$("#<%=btnSelect.ClientID%>").click(function(evt) {
$("#<%=lstSuppliers.ClientID%> > *").removeClass("highlight");
var iType = $("#<%=ddlType.ClientID%>").val();
switch (iType) {
case "1":
$("#<%=lstSuppliers.ClientID%> :first-child").addClass("highlight");
break;
case "2":
$("#<%=lstSuppliers.ClientID%> :last-child").addClass("highlight");
break;
case "3":
$("#<%=lstSuppliers.ClientID%> :lt(4)").addClass("highlight");
break;
case "4":
$("#<%=lstSuppliers.ClientID%> :gt(7)").addClass("highlight");
break;
case "5":
$("#<%=lstSuppliers.ClientID%> :nth-child(5)").addClass("highlight");
break;
case "6":
$("#<%=lstSuppliers.ClientID%> :nth-child(even)").addClass("highlight");
break;
case "7":
$("#<%=lstSuppliers.ClientID%> :nth-child(odd)").addClass("highlight");
break;
default:
alert("Please select the type of element");
}
evt.preventDefault();
});
});
</script>
How it works…
web 页面工作原理如下:
-
Run the application and right-click on the page in the browser to go to View Source. At runtime, the
ListBoxcontrol will be rendered as theselectandoptionHTML elements, as shown here:![How it works…]()
-
The entire action of the page lies in the event handler for the
clickevent of the Select Items button:$("#<%=btnSelect.ClientID%>").click(function (evt) {…});当您单击此按钮时,首先,
ListBox控件(option元素)的所有子元素的 CSS 样式将使用removeClass函数重置:$("#<%=lstSuppliers.ClientID%> > *").removeClass("highlight"); -
检索
DropDownList控件的选定值以查找所需的选择类型:var iType = $("#<%=ddlType.ClientID%>").val(); -
switch-case 语句帮助您根据下拉列表中所选的项目选择子元素的不同选择:
-
如果在下拉列表中选择的项目是First,那么第一个选项元素将使用以下代码高亮显示:
$("#<%=lstSuppliers.ClientID%> :first-child").addClass("highlight"); -
如果选中的项目是最后,最后一个选项元素将使用以下代码突出显示:
$("#<%=lstSuppliers.ClientID%> :last-child").addClass("highlight"); -
If the item selected is Less Than, all option elements that are less than index 4—that is, items with indices 0 to 3, are highlighted using the following code:
$("#<%=lstSuppliers.ClientID%> :lt(4)").addClass("highlight");注意事项
为了简单起见,这里对索引进行了硬编码。
-
If the item selected is Greater Than, all option elements that are greater than index 7—that is, items excluding those with indices 0 to 7, are highlighted using this code:
$("#<%=lstSuppliers.ClientID%> :gt(7)").addClass("highlight");注意事项
为了简单起见,这里对索引进行了硬编码。
-
If the item selected is Nth Item, the fifth option element is highlighted using the following code:
$("#<%=lstSuppliers.ClientID%> :nth-child(5)").addClass("highlight");注意事项
为了简单起见,这里对索引进行了硬编码。
-
如果选中的项目是偶数项目,则所有具有偶数索引的选项元素将使用以下代码高亮显示:
$("#<%=lstSuppliers.ClientID%> :nth-child(even)").addClass("highlight"); -
如果选中的项目是奇数项,所有带有奇数索引的选项元素将使用以下代码突出显示:
$("#<%=lstSuppliers.ClientID%> :nth-child(odd)").addClass("highlight");
-
-
最后,由于按钮
click事件,执行evt.preventDefault()将阻止页面的提交。
参见 also
- 选择一个使用 ID 的控件并显示其值 recipe
启用/禁用 web 窗体上的控件
这个配方演示了如何在 web 窗体上动态启用/禁用控件,以响应窗体上其他控件触发的事件。 本例中使用的结构如下:
|构造
|
类型
|
描述
|
| --- | --- | --- |
| $("#identifier") | jQuery 选择器 | 这将基于其ID选择一个元素。 |
| $(this) | jQuery 对象 | 它引用当前 jQuery 对象 |
| :checked | jQuery 选择器 | 这将选择选中的输入元素 |
| .click() | jQuery 事件绑定 | 这将处理程序绑定到元素的click事件 |
| .find() | jQuery 方法 | 这将查找匹配筛选器的所有元素 |
| .is() | jQuery 方法 | 如果匹配的元素满足给定条件,则返回一个布尔值 |
| prop(propertyName) or``.prop(propertyName, value) | jQuery 方法 | 这将为第一个匹配的元素返回指定属性的值,或者为所有匹配的元素设置指定属性的值 |
| .val() | jQuery 方法 | 返回第一个匹配元素的值,或者设置每个匹配元素的值 |
准备
让我们创建一个作业应用表单来显示 ASP 的启用和禁用.NET 控件:
-
We will build a simple job application form for a company, as shown here:
![Getting ready]()
-
Clicking on certain controls disables other controls on the form, as shown in the following screenshot:
![Getting ready]()
-
首先,创建一个ASP.NET Web 应用项目使用空模板,且名称项目
Recipe6(或任何其他合适的名称)。 -
添加一个Web 表单到项目中,并将命名其
Default.aspx。 -
创建一个
Scripts文件夹,并添加 jQuery 文件(库的调试和发布版本)。 -
使用或者
<script>块或者ScriptManager控件的形式包含 jQuery 库,如第一章,中所述.NET。 -
打开
Default.aspx的 web 表单设计模式,和所需的控件拖放到导航到工具箱|标准创建 web 表单,如前面的屏幕截图所示。 网页表单的标记如下:<table> <tr> <td> <asp:Label ID="lblName" runat="server" Text="Name"></asp:Label> </td> <td> <asp:TextBox ID="txtName" runat="server" Width="220px"></asp:TextBox> </td> </tr> <tr> <td> <asp:Label ID="lblPermAddr" runat="server" Text="Permanent Address"></asp:Label> </td> <td> <asp:TextBox ID="txtPermAddr" runat="server" Width="220px" TextMode="MultiLine"></asp:TextBox> </td> </tr> <tr> <td> <asp:Label ID="lblMailingAddr" runat="server" Text="Mailing Address" /> </td> <td> <asp:CheckBox ID="chkMailingAddr" runat="server" Text="Same as above" /> <br /> <asp:TextBox ID="txtMailingAddr" runat="server" Width="220px" TextMode="MultiLine"></asp:TextBox> </td> </tr> <tr> <td> <asp:Label ID="lblTravel" runat="server" Text="Willing to travel?" /> </td> <td> <asp:RadioButtonList ID="rdTravel" runat="server"> <asp:ListItem Text="Yes" Value="Yes"></asp:ListItem> <asp:ListItem Text="No" Value="No"></asp:ListItem> </asp:RadioButtonList> <br /> <asp:DropDownList ID="ddlTravel" runat="server"> <asp:ListItem Text="10%"></asp:ListItem> <asp:ListItem Text="25%"></asp:ListItem> <asp:ListItem Text="50%"></asp:ListItem> <asp:ListItem Text="75%"></asp:ListItem> </asp:DropDownList> <br /> </td> </tr> <tr> <td> <asp:Label ID="lblMode" runat="server" Text="Mode of Contact" /> </td> <td> <asp:CheckBox ID="chkEmail" runat="server" Text="Email" Value="Email" Checked="true" /> <asp:CheckBox ID="chkPhone" runat="server" Text="Phone" Value="Phone" Checked="true" /> </td> </tr> <tr> <td> <asp:Label ID="lblEmail" runat="server" Text="Email" /> </td> <td> <asp:TextBox ID="txtEmail" runat="server" Width="220px"></asp:TextBox> </td> </tr> <tr> <td> <asp:Label ID="lblPhone" runat="server" Text="Phone" /> </td> <td> <asp:TextBox ID="txtPhone" runat="server" Width="220px"></asp:TextBox> </td> </tr> <tr> <td colspan="2"> <asp:Button ID="btnSubmit" runat="server" Text="Submit" /> <asp:Button ID="btnReset" runat="server" Text="Reset" /> </td> </tr> </table>
怎么做……
在页面中包含库后的<script>块中包含和的 jQuery 代码:
<script type="text/javascript">
$(document).ready(function() {
$("#<%=chkMailingAddr.ClientID%>").click(function() {
if ($(this).is(":checked"))
$("#<%=txtMailingAddr.ClientID%>").prop("disabled", true);
else
$("#<%=txtMailingAddr.ClientID%>").prop("disabled", false);
});
$("#<%=rdTravel.ClientID%>").click(function() {
var strTravel = $(this).find(":checked").val();
if (strTravel == "No")
$("#<%=ddlTravel.ClientID%>").prop("disabled", true);
else
$("#<%=ddlTravel.ClientID%>").prop("disabled", false);
});
$("#<%=chkEmail.ClientID%>").click(function() {
if (!$(this).is(":checked"))
$("#<%=txtEmail.ClientID%>").prop("disabled", true);
else
$("#<%=txtEmail.ClientID%>").prop("disabled", false);
});
$("#<%=chkPhone.ClientID%>").click(function() {
if (!$(this).is(":checked"))
$("#<%=txtPhone.ClientID%>").prop("disabled", true);
else
$("#<%=txtPhone.ClientID%>").prop("disabled", false);
});
});
</script>
How it works…
网页的工作原理如下:
-
Save the application and launch it using F5. In the Mailing Address section, on checking the Same as above field, the Mailing Address textbox is disabled as follows:
![How it works…]()
注意事项
类似地,取消选中该字段时,将启用邮寄地址文本框。
-
这是通过为
CheckBox控件的click事件编写事件处理程序实现的。 当复选框被选中或未选中时,将触发click事件: -
In the preceding event handler, firstly, it is determined whether the field is checked using the following code:
if ($(this).is(":checked"))如果上述条件为
true,为了禁用邮寄地址文本框,使用prop()方法为其disabled属性赋值true,如下所示:$("#<%=txtMailingAddr.ClientID%>").prop("disabled", true);类似地,如果复选框未选中,则通过为其
disabled属性分配false值来启用邮寄地址文本框,如下所示:$("#<%=txtMailingAddr.ClientID%>").prop("disabled", false); -
For the Willing to Travel radio button, when the No option is selected, the dropdown list below the field is disabled, as shown in the following figure:
![How it works…]()
-
这可以通过将事件处理程序附加到
RadioButtonList:$("#<%=rdTravel.ClientID%>").click(function () {…});的
click事件来实现。 -
When the preceding event handler is invoked, the selected value is first determined using this code:
var strTravel = $(this).find(":checked").val();如果选择的值为不为,则通过将
true值附加到其disabled属性上禁用下拉列表,如下所示:if (strTravel == "No") $("#<%=ddlTravel.ClientID%>").prop("disabled", true);否则,通过在其
disabled属性上附加false值来启用下拉列表,如下所示:else $("#<%=ddlTravel.ClientID%>").prop("disabled", false); -
When the two checkbox controls in the Mode of Contact field are unchecked, the corresponding textbox field is disabled, that is, unchecking the Email checkbox disables the Email textbox. Similarly, unchecking the Phone checkbox disables the Phone textbox as follows:
![How it works…]()
-
这可以通过将各自的事件处理程序附加到
Email和Phone复选框控件上,如下所示: -
In the preceding event handlers, it is first required to determine whether the respective
CheckBoxcontrol is unchecked using the following code:if (!$(this).is(":checked"))如果相应的复选框未选中,则通过将
true值附加到TextBox控件的disabled属性来禁用TextBox控件,如下所示:-
Email字段:$("#<%=txtEmail.ClientID%>").prop("disabled", true); -
Phone字段:$("#<%=txtPhone.ClientID%>").prop("disabled", true);
否则,通过将
false值附加到disabled属性来启用相应的TextBox控件,如下所示:-
Email字段:$("#<%=txtEmail.ClientID%>").prop("disabled", false); -
Phone字段:$("#<%=txtPhone.ClientID%>").prop("disabled", false);
-
参见 also
- 通过属性配方选择控件
在 MVC 应用中使用选择器
所以到目前为止,所有的菜谱都是基于使用选择器和 ASP。 净 web 表单。 接下来,我们介绍一个示例来演示在 ASP 中使用选择器。 净 MVC 应用。 本例中使用的结构如下:
|构造
|
类型
|
描述
|
| --- | --- | --- |
| $(#identifier) | jQuery 选择器 | 这将基于其ID选择一个元素。 |
| $(this) | jQuery 对象 | 它引用当前 jQuery 对象 |
| :checked | jQuery 选择器 | 这将选择选中的输入元素 |
| .click() | jQuery 事件绑定 | 这将处理程序绑定到元素的click事件 |
| .css() | jQuery 方法 | 这将获取第一个匹配元素的 CSS 属性,或者为每个匹配元素设置一个或多个 CSS 属性 |
| .each() | jQuery 方法 | 这将遍历匹配的元素,并为每个元素执行一个函数 |
| event.preventDefault() | jQuery 方法 | 这将防止触发事件的默认动作 |
| .html() | jQuery 方法 | 这将返回第一个匹配元素的 HTML 内容,或者设置每个匹配元素的 HTML 内容 |
| .prop(propertyName) or``.prop(propertyName, value) | jQuery 方法 | 这将为第一个匹配的元素返回指定属性的值,或者为所有匹配的元素设置指定属性的值 |
| :radio | jQuery 选择器 | 这将选择 radio 类型的输入元素 |
| .val() | jQuery 方法 | 返回第一个匹配元素的值,或者设置每个匹配元素的值 |
准备
要在 MVC 应用中使用选择器,请遵循以下步骤:
-
Let's create a simple MVC application for a Feedback Form to be completed by a user, as shown in the following screenshot:
![Getting ready]()
-
When you click on the Submit button, the validation of the form fields is done using jQuery, and the page will throw an error message giving the details of the fields that are required to be completed, as shown here:
![Getting ready]()
-
If all the fields are completed, the validation will go through, and the user will see a confirmation screen, as shown here:
![Getting ready]()
-
要开始,在 Visual Studio 中通过导航到文件|new|project创建一个新项目。 从对话框中选择ASP.NET Web 应用,并键入
Recipe7(或任何其他合适的名称)作为应用的名称。 -
From the following dialog box, select the Empty template and the MVC checkbox, as shown in the following screenshot, and click on the OK button:
![Getting ready]()
-
We need to add a model to the feedback form, two views (corresponding to the two screens in the application) and a controller. Let's start by adding a model by right-clicking on the Models folder in Solution Explorer and navigating to New | Class. name the class
FeedbackForm.vb(VB) orFeedbackForm.cs(C#), and add the following properties that correspond to the fields on the feedback form:对于 VB,代码如下:
Public Class FeedbackForm Public Property Name As String Public Property Email As String Public Property ImprovementArea As String Public Property Rating As String End Class对于 c#,代码如下:
public class FeedbackForm { public string Name { get; set; } public string Email { get; set; } public string ImprovementArea { get; set; } public string Rating { get; set; } } -
Now, add a controller by right-clicking on the Controllers folder in Solution Explorer and navigating to New | Controller. From the dialog box, select MVC 5 Controller – Empty, and click on the Add button:
![Getting ready]()
-
In the following dialog box, enter
DefaultControllerin the Controller name field, and click on the Add button:![Getting ready]()
-
Add the following
Actionmethod inDefaultController.vb(VB) orDefaultController.cs(C#):对于 VB,代码如下:
Function Index() As ActionResult Return View() End Function Function HandleForm(ByVal formData As FeedbackForm) As ActionResult ViewData("Name") = formData.Name ViewData("Email") = formData.Email ViewData("ImprovementArea") = formData.ImprovementArea ViewData("Rating") = formData.Rating Return View() End Function对于 c#,代码如下:
public ActionResult Index() { return View(); } public ActionResult HandleForm(FeedbackForm formData) { ViewData["Name"] = formData.Name; ViewData["Email"] = formData.Email; ViewData["ImprovementArea"] = formData.ImprovementArea; ViewData["Rating"] = formData.Rating; return View(); } -
To add a view, right-click by navigating to the Views | Default folder in Solution Explorer, and go to Add | View. In the dialog box that is launched, enter
Indexfor the View name, and click on the Add button:

- 类似地,通过导航到视图|默认文件夹添加一个视图,并将视图命名为
HandleForm。 这个视图是确认页面,一旦用户提交了反馈表单,就会启动这个页面。 - 在项目中创建一个
Scripts文件夹,并在此文件夹中包含 jQuery 库文件。 - 在 Index 视图中使用绑定方法将 jQuery 库包含进来,详见第一章,.NET、或使用
<script>标记。 - Add a
<form>element to the Index view using HTML extensions with the Razor syntax, as follows:
对于 VB,代码如下:
```
@Imports System.Web.Optimization
@Code
ViewData("Title") = "Feedback Form"
End Code
@Scripts.Render("~/Scripts/jquery")
<h2>Feedback Form</h2>
<table>
@Using Html.BeginForm("HandleForm", "Default")
@
<text>
<tr>
<td>@Html.Label("Name")</td>
<td>@Html.TextBox("Name")</td>
</tr>
<tr>
<td>@Html.Label("Email")</td>
<td>@Html.TextBox("Email")</td>
</tr>
<tr>
<td>@Html.Label("What can we do better?")</td>
<td>@Html.TextArea("ImprovementArea", New With {.cols = 50, .rows = 5})</td>
</tr>
<tr>
<td>@Html.Label("Please rate our service")</td>
<td>
@Html.RadioButton("Rating", "5")<label> Very Good</label>
@Html.RadioButton("Rating", "4")<label> Good</label>
@Html.RadioButton("Rating", "3")<label> Average</label>
@Html.RadioButton("Rating", "2")<label> Bad</label>
@Html.RadioButton("Rating", "1")<label> Very Bad</label>
</td>
</tr>
<tr>
<td colspan = "2"> <input id="btnSubmit" type="submit" value="Submit" /></td>
</tr>
<tr>
<td colspan = "2" >
<div id="ErrorMessage"></div>
</td>
</tr>
</text>
End Using
</table>
```
对于 c#,代码如下:
```
@using System.Web.Optimization;
@{
ViewBag.Title = "Feedback Form";
}
@Scripts.Render("~/Scripts/jquery")
<h2>Feedback Form</h2>
<table>
@using (Html.BeginForm("HandleForm","Default"))
{
<tr>
<td>@Html.Label("Name")</td>
<td>@Html.TextBox("Name")</td>
</tr>
<tr>
<td>@Html.Label("Email")</td>
<td>@Html.TextBox("Email")</td>
</tr>
<tr>
<td>@Html.Label("What can we do better?")</td>
<td>@Html.TextArea("ImprovementArea",new { @cols=50, @rows=5}) </td>
</tr>
<tr>
<td>@Html.Label("Please rate our service")</td>
<td>@Html.RadioButton("Rating", "5") <label> Very Good</label>
@Html.RadioButton("Rating", "4") <label> Good</label>
@Html.RadioButton("Rating", "3") <label> Average</label>
@Html.RadioButton("Rating", "2") <label> Bad</label>
@Html.RadioButton("Rating", "1")<label> Very Bad</label>
</td>
</tr>
<tr>
<td colspan="2"><input id="btnSubmit" type="submit" value="Submit" /></td>
</tr>
<tr>
<td colspan="2">
<div id="ErrorMessage"></div>
</td>
</tr>
}
</table>
```
- Add the following markup to the
HandleFormview:
对于 VB,代码如下:
```
@Code
ViewData("Title") = "Feedback Submission"
End Code
<h2>Thank you for your Feedback!</h2>
<p>We have received the following:</p>
<p><label>Name: </label>@Html.Encode(ViewData("Name"))</p>
<p><label>Email: </label>@Html.Encode(ViewData("Email"))</p>
<p>
<label>What we can do better?</label><br />
@Html.Encode(ViewData("ImprovementArea"))
</p>
<p>
<label>Please rate our service: </label>
@If ViewData("Rating").Equals("5") Then
@:<label>Very Good</label>
ElseIf ViewData("Rating").Equals("4")
@:<label>Good</label>
ElseIf ViewData("Rating").Equals("3")
@:<label>Average</label>
ElseIf ViewData("Rating").Equals("2")
@: <label>Bad</label>
ElseIf ViewData("Rating").Equals("1")
@: <label>Very Bad</label>
End If
</p>
<p> Thank you For taking the time To write To us.</p>
```
对于 c#,代码如下:
```
@{
ViewBag.Title = "Feedback Submission";
}
<h2>Thank you for your Feedback!</h2>
<p>We have received the following:</p>
<p><label>Name: </label>@Html.Encode(ViewData["Name"])</p>
<p><label>Email: </label>@Html.Encode(ViewData["Email"])</p>
<p><label>What we can do better?</label><br/>
@Html.Encode(ViewData["ImprovementArea"])
</p>
<p><label>Please rate our service: </label>
@if (ViewData["Rating"].Equals("5"))
{
<label>Very Good</label>
}
else if (ViewData["Rating"].Equals("4"))
{
<label>Good</label>
}
else if (ViewData["Rating"].Equals("3"))
{
<label>Average</label>
}
else if (ViewData["Rating"].Equals("2")){
<label>Bad</label>
}
else if (ViewData["Rating"].Equals("1")){
<label>Very Bad</label>
}
</p>
<p> Thank you for taking the time to write to us.</p>
```
怎么做……
在页面中包含库后,在<script>块中包含的代码:
<script type="text/javascript">
$(document).ready(function () {
$("#btnSubmit").click(function (evt) {
var strMessage = "";
if ($("#Name").val() == "")
strMessage = strMessage + "Name<br/>";
if ($("#Email").val() == "")
strMessage = strMessage + "Email<br/>";
if ($("#ImprovementArea").val() == "")
strMessage = strMessage + "What can we do better?<br/>";
var bChecked = false;
$(":radio").each(function () {
if ($(this).prop("checked")){
bChecked = true;
}
});
if (!bChecked)
strMessage = strMessage + "Please rate our service<br/>";
if (strMessage != "") {
strMessage = "<br/>Please complete the following fields: <br/><br/>" + strMessage;
$("#ErrorMessage").html(strMessage);
$("#ErrorMessage").css("color", "#FF0000");
evt.preventDefault();
}
});
});
</script>
How it works…
MVC 中反馈表单的工作原理如下:
-
要运行应用,右键单击Solution Explorer中的Index视图,然后选择view in Browser。 结果,反馈表单加载到浏览器窗口中。
-
当用户单击Submit按钮时,将执行按钮
click的事件处理程序:$("#btnSubmit").click(function (evt) {…}); -
jQuery 代码验证表单中的每个字段。 一个
strMessage字符串变量跟踪所有未填充的字段:var strMessage = ""; if ($("#Name").val() == "") strMessage = strMessage + "Name<br/>"; if ($("#Email").val() == "") strMessage = strMessage + "Email<br/>"; if ($("#ImprovementArea").val() == "") strMessage = strMessage + "What can we do better?<br/>"; -
要测试单选按钮列表是否被选中,我们循环遍历每个单选按钮,并使用
.prop()方法来确定选中的属性是否为true:var bChecked = false; $(":radio").each(function() { if ($(this).prop("checked")) { bChecked = true; } }); if (!bChecked) strMessage = strMessage + "Please rate our service<br/>"; -
最后,如果在页面上发现验证错误—也就是说,如果
strMessage非空,错误将显示在表单末尾的 div 区域中。 使用.css()方法将错误消息的字体颜色更改为红色:if (strMessage != "") { strMessage = "<br/>Please complete the following fields: <br/><br/>" + strMessage; $("#ErrorMessage").html(strMessage); $("#ErrorMessage").css("color", "#FF0000"); evt.preventDefault(); } -
为了防止在出现验证错误时提交表单,使用了
.preventDefault()方法。
参见 also
- 选择一个使用 ID 的控件并显示其值 recipe**
三、使用 jQuery 处理事件
本章介绍在 ASP 中处理事件时的一些重要概念。 净使用 jQuery。 本章将讨论以下配方:
- 响应鼠标事件
- 响应键盘事件
- 响应表单事件
- 使用事件委托将事件附加到未来的控件
- 只运行一次活动
- 以编程方式触发事件
- 使用事件传递数据并使用事件命名空间
- 分离的事件
简介
事件是当用户与网页交互或某些里程碑(如在浏览器中加载页面)完成时发生的动作。 移动鼠标、按下一个键、单击按钮或链接、在字段中键入文本或提交表单,这些都对应于页面生命周期中引发的常见事件。 这些事件可以是用户发起的,也可以是系统发起的。
事件处理程序是当特定事件发生时执行的函数。 为特定事件编写事件处理程序称为连接或绑定事件。 事件处理程序帮助开发人员利用事件并编写所需的操作。
当处理事件时,务必熟悉一种称为事件委托的机制。 此特性使您能够将单个事件处理程序附加到父元素,而不是将单个事件处理程序附加到每个子元素。 例如,考虑一个无序列表,即一个包含 100 个列表项的ul元素。 与向页面附加 100 个单独的事件处理程序(即每个列表项一个事件处理程序)不同,可以将单个事件处理程序附加到父列表(即无序列表)。 除了优化页面上所需的事件处理程序的数量外,事件委托还可以帮助您将事件连接到现在不存在但将在将来添加的子元素。
事件委派之所以可能是因为事件冒泡。 事件冒泡是这样一个过程:在子元素中发生的事件传递到其父元素,然后传递到其父元素的父元素,以此类推,直到它到达根元素:窗口。 假设页面上有一个表格元素。 当你点击一个表细胞,也就是说,当你点击td元素,click事件将泡沫 DOM 树,这是td——【病人】tr——>table——>body——>html——【t16.1】window,如下图所示:

因此,td元素的click事件可以被父table元素拦截,并且附加到表的单个处理程序可以作为所有单个表单元的代表。
然而,某些应用可能需要在特定级别终止事件冒泡。 因此,jQuery 为事件提供了一个.stopPropagation()方法,该方法可以使事件停止在 DOM 树中冒泡。
注意事项
在https://api.jquery.com/category/events可以找到更多关于 jQuery 事件的信息。
jQuery 事件绑定
jQuery 1.7+提供了.on()方法来响应事件。 在此方法之前,我们使用了其他事件结合剂,如.bind(),.live(),.delegate()。 然而,这些方法已被弃用,建议您使用 jQuery 1.7+中的.on()进行事件绑定。 使用这种方法的方法有很多种,如下:
-
Attaching a single event to a handler
例如,将处理程序附加到按钮控件的
click事件,如下所示:$ ("#btnTest").on ("click",function (){...}); -
Attaching multiple events to a handler
例如,将相同的处理程序附加到图像控件的
mouseover和mouseout事件,如下所示:$ ("#imgTest").on ("mouseover mouseout", function (){...}); -
Attaching different events to different handlers
例如,将不同的处理程序附加到图像控件的
mouseover和mouseout事件,如下所示:$ ("#imgTest").on ({ mouseover: function (){...}, mouseout: function (){...} }); -
Event delegation
例如,将一个事件处理程序附加到父表,而不是每个单独的表行,如下所示:
$("#tblTest").on("click", "tr", function(){...}); -
Passing data to events
例如,将数据作为 JSON 字符串传递给事件,如下所示:
$("btnTest").on("click",{var1: "val1", var2: "val2"}, function(event){...});
现在,让我们转向食谱,进一步了解绑定。
响应鼠标事件
这个配方演示了如何为网页上发生的常见鼠标事件(如mouseover和mouseout)编写事件处理程序。 本例中使用的结构总结如下:
构造
|
类型
|
描述
|
| --- | --- | --- |
| $(".class") | jQuery 选择器 | 它匹配指定 CSS 类的所有元素。 |
| $(this) | jQuery 对象 | 这是指当前的 jQuery 对象 |
| .attr("name") 或.attr("name", "value") | jQuery 方法 | 这将返回一个字符串,其中包含第一个匹配元素所需属性的值。它还可以用于将属性设置为所需的值。 |
| .appendTo() | jQuery 方法 | 这个将每个匹配的元素追加到目标元素的末尾。 |
| input | jQuery 选择器 | 这将选择所有的输入元素。 |
| mouseout | jQuery 的事件 | 当鼠标指针离开控件时触发此操作。 它对应于 JavaScript 的mouseout事件。 |
| mouseover | jQuery 的事件 | 当鼠标指针进入控件时触发。 它对应于 JavaScript 的mouseover事件。 |
| .on() | jQuery 事件绑定 | 这将一个或多个事件的事件处理程序附加到匹配的元素。 |
| .parents() | jQuery 方法 | 这将选择 DOM 树中匹配元素的祖先。 |
| .remove() | jQuery 方法 | 这将从 DOM 中删除匹配的元素。 |
| .removeAttr() | jQuery 方法 | 这将从匹配的元素中删除特定的属性。 |
| .text() | jQuery 方法 | 这将返回每个匹配元素的组合文本内容,或者设置每个匹配元素的文本内容。 |
| :text | jQuery 选择器 | 这将选择类型为 text 的所有输入元素。 |
准备
要显示页面上鼠标事件的处理,请遵循以下步骤:
-
Let's start by creating a simple registration page for students, as shown in the following screenshot:
![Getting ready]()
-
By moving the mouse pointer over any
TextBoxcontrol on the page, the corresponding tooltip is displayed using jQuery, as shown here:![Getting ready]()
-
When the mouse pointer moves out of the respective
TextBoxcontrol, the tooltip becomes invisible.注意事项
当使用控件的
ToolTip属性时, NET 默认显示一个简单的工具提示。 这个配方增强了默认的工具提示,并对其应用自定义样式。 -
要构建此页面,请创建一个ASP.NET Web 应用项目在 Visual Studio 中使用空模板,并将项目命名为
Recipe1(或其他合适的名称)。 -
将 jQuery 库添加到项目的
Scripts文件夹中。 -
创建一个新的 web 表单,并在表单中包含 jQuery 库。
-
Add the following markup to the form to create the registration fields:
<table> <tr><td>Student Name:</td> <td><asp:TextBox ID="txtStudentName" runat="server" ToolTip="Name as in your Student Card"></asp:TextBox> </td> </tr> <tr><td>Student ID:</td> <td><asp:TextBox ID="txtStudentID" runat="server" ToolTip="Enter your 10 digit Student ID"></asp:TextBox> </td> </tr> <tr><td>Email:</td> <td><asp:TextBox ID="txtEmail" runat="server" ToolTip="Email address for receiving registration notification"></asp:TextBox> </td> </tr> <tr> <td colspan="2"> <asp:Button ID="btnRegister" runat="server" Text="Register" /> </td> </tr> </table>注意,每个
TextBox控件都定义了一个ToolTip文本。 这是当用户将鼠标指针移动到相应的TextBox控件时将显示的文本。 -
在页面的
head元素中,向工具提示添加一个style元素,如下面的代码所示:
怎么做……
将下面的 jQuery 代码添加到页面的<script>块中:
<script type="text/javascript">
$(document).ready(function () {
$("input:text").on("mouseover",function(){
var strTitle = $(this).attr("title");
$(this).removeAttr("title");
$("<div class='tooltip'></div>").text(strTitle).appendTo($(this).parents("tr"));
});
$("input:text").on("mouseout", function () {
var strTitle = $(".tooltip").text();
$(this).attr("title", strTitle);
$(".tooltip").remove();
});
});
</script>
How it works…
该网页的工作原理如下:
-
使用Ctrl+S保存应用,并使用F5运行它。 页面在浏览器窗口中加载,通过在控件中移动鼠标指针,可以在
TextBox控件旁边看到相应的工具提示。 通过将鼠标指针移出控件,工具提示将消失。 -
This is made possible by attaching events to both the
mouseoverandmouseoutproperties of theTextBoxcontrols as follows:$("input:text").on("mouseover",function(){…}); $("input:text").on("mouseout", function(){…});提示
不使用带有
mouseover和mouseout事件的.on()事件绑定器,可以使用悬停,它提供了一种快捷机制来连接进入和离开元素的鼠标指针的事件。 -
In the event handler for
mouseover, we need to retrieve theToolTiptext and display it in adivarea next to theTextBoxcontrol. At runtime, theToolTipproperty of an ASP.NET control is rendered as atitleproperty. Thus, thetitleattribute of the control is retrieved and saved in a local variable:var strTitle = $(this).attr("title");以防止 ASP。 在显示默认工具提示时,从相应的控件中删除
title属性。 删除该属性是可以的,因为我们已经将其值保存在strTitle变量中:$(this).removeAttr("title"); -
现在,用
tooltipCSS 类创建一个div元素。 该类包含用于显示工具提示的必要修饰。 将其文本设置为工具提示文本strTitle。 将这个div元素附加到父表行,即TextBox控件的tr元素:$("<div class='tooltip'></div>").text(strTitle).appendTo($(this).parents("tr")); -
在
mouseout的事件处理程序中,我们需要删除在第 4 步中创建的div元素,并恢复控件的title属性。 因此,首先,使用 CSS 类选择器检索工具提示文本:var strTitle = $(".tooltip").text(); -
Add this tooltip text to the
titleattribute of theTextBoxcontrol. This is to ensure that the tooltip text for a particularTextBoxcontrol is not lost:$(this).attr("title", strTitle);现在,可以安全地删除第 4 步中创建的
div元素,以便通过移出鼠标指针,它将消失。 同样,CSS 类选择器在删除的过程中用于访问div元素:$(".tooltip").remove();
参见 also
响应键盘事件配方
响应键盘事件
这个配方演示了如何为一个常见的键盘事件keyup编写一个事件处理程序,该事件处理程序在一个键被释放时触发。 本例中使用的构造如下:
构造
|
类型
|
描述
|
| --- | --- | --- |
| $("#identifier") | jQuery 选择器 | 这将使用其 ID 选择一个元素。 |
| $(this) | jQuery 对象 | 它引用当前 jQuery 对象。 |
| .addClass() | jQuery 方法 | 这将向每个匹配的元素添加指定的 CSS 类。 |
| keyup | jQuery 的事件 | 当一个键被释放时,这个将被触发。 它对应于 JavaScript 的keyup事件。 |
| .length | JavaScript 的财产 | 这会返回字符串的长度。 |
| .on() | jQuery 事件绑定 | 这将一个或多个事件的事件处理程序附加到匹配的元素。 |
| .prop(propertyName)或.prop(propertyName, value) | jQuery 方法 | 这将为第一个匹配的元素返回指定属性的值,或者为所有匹配的元素设置指定属性的值。 |
| .substring() | JavaScript 函数 | 它提取一个字符串的子字符串。 |
| .text() | jQuery 方法 | 这将返回每个匹配元素的组合文本内容,或者设置每个匹配元素的文本内容。 |
| .toString() | JavaScript 函数 | 这将对象转换为字符串数据类型。 |
| .val() | jQuery 方法 | 返回第一个匹配元素的值,或者设置每个匹配元素的值。 |
准备
要创建一个响应键盘事件的页面,请遵循以下步骤:
-
We will create the following form that keeps a check on the number of characters entered by a user in a multiline textbox field. When characters are entered in the field, the second textbox displays the number of the remaining characters that can be entered, with the limit set to 100, as shown in the following screenshot:
![Getting ready]()
当达到最大字符数,即 100,计数减少为 0,多行文本框字段阻止更多字符的输入,如下图所示:
![Getting ready]()
-
要开始使用这个应用,请创建一个新的ASP.NET Web 应用项目在 Visual Studio 中使用空模板,并将其命名为
Recipe2(或其他合适的名称)。 -
在项目中创建一个
Scripts文件夹,并将 jQuery 库文件复制到此文件夹中。 -
添加一个新的 web 表单到项目中,并在表单中包含 jQuery 库。
-
Add the following markup to the web form to create the page, as shown in the preceding screenshot:
<h2> Enter your comments below:</h2> <asp:TextBox ID="txtComments" runat="server" Columns="40" Rows="5" TextMode="MultiLine"></asp:TextBox> <br/><br/> <asp:Label ID="lblCount" runat="server" Text="Characters remaining: "></asp:Label><asp:TextBox ID="txtCount" runat="server" MaxLength="3" Width="50px"></asp:TextBox> <br/><br/> <asp:Label ID="lblError" runat="server"></asp:Label>注意,
txtComments字段的TextMode属性被设置为MultiLine。 用于显示剩余字符计数的txtCount文本框将MaxLength设置为3,因为它将仅用于显示从 0 到 100 的数字。 在表单的末尾有一个lblError标签控件,用于在字符数量超过允许的最大限制时显示错误消息。 -
Add the following CSS style to the page:
<style type="text/css"> .red{ color:red; } </style>此样式将应用于错误消息。
怎么做……
在页面的<script>块中包含以下 jQuery 代码:
<script type="text/javascript">
$(document).ready(function () {
$("#<%=txtCount.ClientID%>").val("100");
$("#<%=txtCount.ClientID%>").prop("readonly",true);
$("#<%=lblError.ClientID%>").addClass("red");
$("#<%=txtComments.ClientID%>").on("keyup", function ()
{
var maxChars = 100;
var count = $(this).val().length;
var remChars = maxChars - count;
if (remChars >= 0) {
$("#<%=txtCount.ClientID%>").val(remChars.toString());
}else{
$(this).val($(this).val().substring(0,maxChars));
$("#<%=txtCount.ClientID%>").val("0");
$("#<%=lblError.ClientID%>").text("You have reached the maximum characters allowed");
}
});
});
</script>
How it works…
页面工作原理如下:
-
Save the page using Ctrl + S, and run it using F5. When the document is ready, the number of remaining characters in the textbox below the comments field is set to
100characters in the following statement:$("#<%=txtCount.ClientID%>").val("100");这个文本框也被设置为
readonly,这样用户就不能对其内容进行更改:$("#<%=txtCount.ClientID%>").prop("readonly",true); -
一个 CSS 类被添加到错误标签中,因此它以红色显示错误消息:
$("#<%=lblError.ClientID%>").addClass("red"); -
An event handler is wired to the
keyupevent of the multiline textbox using the.on()method as follows:$("#<%=txtComments.ClientID%>").on("keyup", function () {...});提示
使用
keyup事件代替keydown和keypress事件,以便在字符添加到文本框后进行字符计数计算。 当使用keydown或keypress时,jQuery 代码在字符添加到文本框之前执行,因此给出不正确的字符计数。 试着自己把keyup改为keydown或keypress。 -
在前一个事件处理程序中,首先声明一个变量来存储多行文本框中允许的最大字符,并将其值设置为100字符:
var maxChars = 100; -
多行文本框中任意时刻的字符数将保存在另一个变量中:
var count = $(this).val().length; -
最大字符数和实际字符数之间的差值被计算并保存在第三个变量中:
var remChars = maxChars - count; -
If the difference is positive or zero, the number of available characters, that is, the difference calculated earlier, is displayed in the second textbox below the comments field:
if (remChars >= 0) { $("#<%=txtCount.ClientID%>").val(remChars.toString()); }否则,只使用
substring函数从注释字段中提取前 100 个字符并显示在字段中。 在第二个文本框中,字符数被设置为0,并且在页面末尾使用标签控件显示一条错误消息:else{ $(this).val($(this).val().substring(0,maxChars)); $("#<%=txtCount.ClientID%>").val("0"); $("#<%=lblError.ClientID%>").text("You have reached the maximum characters allowed"); }
参见 also
响应表单事件配方
响应表单事件
这个配方演示了如何响应在 web 表单上的控件上触发的、focus和blur等事件。 本例中使用的构造如下:
构造
|
类型
|
描述
|
| --- | --- | --- |
| $(this) | jQuery 对象 | 它引用当前 jQuery 对象。 |
| .addClass() | jQuery 方法 | 这会将指定的 CSS 类添加到每个匹配的元素中。 |
| [attribute!= "value"] | jQuery 选择器 | 这将选择指定属性不等于value字符串的元素。 |
| blur | jQuery 的事件 | 当一个元素失去焦点时触发。 它对应于 JavaScript 的blur事件。 |
| .each() | jQuery 方法 | 这将遍历匹配的元素,并为每个元素执行一个函数。 |
| focus | jQuery 的事件 | 当一个元素获得焦点时,它就会触发。 它对应于 JavaScript 的focus事件。 |
| :input | jQuery 选择器 | 它匹配input、button、select和textarea元素。 |
| .on() | jQuery 事件绑定 | 这将一个或多个事件的事件处理程序附加到匹配的元素。 |
| .prop(propertyName)或.prop(propertyName, value) | jQuery 方法 | 这将为第一个匹配的元素返回指定属性的值,或者为所有匹配的元素设置指定属性的值。 |
| .removeClass() | jQuery 方法 | 这将从每个匹配的元素中删除指定的 CSS 类。 |
| .val() | jQuery 方法 | 返回第一个匹配元素的值,或者设置每个匹配元素的值。 |
准备
按照以下步骤创建一个用于事件处理的表单:
-
We will build a very basic account registration form, as shown in the following screenshot:
![Getting ready]()
表单上的文本框字段显示默认文本。 当光标聚焦在一个特定的
TextBox控件上时,默认文本将消失,该控件将以蓝色突出显示,如上面的截图所示。 类似地,当DropDownList控件处于活动状态时,高亮显示也会应用于该控件。当光标移出控件时,如果控件为空,即没有向控件中输入数据,则会用红色高亮显示验证错误,如下图所示:
![Getting ready]()
-
要启动,首先创建一个ASP.NET Web 应用项目在 Visual Studio 中使用空的模板,并将其命名为
Recipe3(或其他合适的名称)。 -
在项目中创建一个
Scripts文件夹,并将 jQuery 库文件复制到此文件夹中。 -
添加一个新的 web 表单到项目中,并在页面中包含 jQuery 库。
-
将以下标记添加到 web 表单:
<table> <tr> <td colspan="2"><asp:Label ID="lblName" runat="server" Text="Name"></asp:Label> </td> </tr> <tr> <td><asp:TextBox ID="txtFirst" runat="server" ToolTip="First"></asp:TextBox> </td> <td><asp:TextBox ID="txtLast" runat="server" ToolTip="Last"></asp:TextBox> </td> </tr> <tr> <td colspan="2"><asp:Label ID="lblEmail" runat="server" Text="Email"></asp:Label> </td> </tr> <tr> <td colspan="2"><asp:TextBox ID="txtEmail" runat="server" ToolTip="@email.com"></asp:TextBox> </td> </tr> <tr> <td colspan="2"><asp:Label ID="lblPassword" runat="server" Text="Password"></asp:Label> </td> </tr> <tr> <td colspan="2"><asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox> </td> </tr> <tr> <td colspan="2"><asp:Label ID="lblConfirmPassword" runat="server" Text="Confirm Password"></asp:Label> </td> </tr> <tr> <td colspan="2"><asp:TextBox ID="txtConfirmPassword" runat="server" TextMode="Password"></asp:TextBox> </td> </tr> <tr> <td colspan="2"><asp:Label ID="lblGender" runat="server" Text="Gender"></asp:Label> </td> </tr> <tr> <td colspan="2"> <asp:DropDownList ID="ddlGender" runat="server"> <asp:ListItem Text="--Please select--" Value=""></asp:ListItem> <asp:ListItem Text="Male" Value="Male"></asp:ListItem> <asp:ListItem Text="Female" Value="Female"></asp:ListItem> </asp:DropDownList> </td> </tr> <tr> <td colspan="2"> <asp:Button ID="btnSubmit" runat="server" Text="Submit" /> <asp:Button ID="btnReset" runat="server" Text="Reset" /> </td> </tr> </table> -
Include the following styles in the
headelement of the page:<style type="text/css"> .active{ border-color:blue; } .invalid{ border-color:red; } .backgroundtext{ color:grey; } </style>样式应用于页面上的当前控件,即具有光标的控件。 样式应用于无效控件:其中没有输入数据的控件。
backgroundtext样式应用于TextBox控件中显示的默认文本。
怎么做……
在页面的<script>块中包含以下 jQuery 代码:
<script type="text/javascript">
$(document).ready(function () {
$(":input[type!=submit]").each(function () {
if ($(this).val() == "") {
$(this).addClass("backgroundtext");
$(this).val($(this).prop("title"));
}
});
$(":input[type!=submit]").on({
focus: function () {
if ($(this).val() == $(this).prop("title")) {
$(this).removeClass("backgroundtext");
$(this).removeClass("invalid");
$(this).val("");
}
$(this).addClass("active");
},
blur: function () {
$(this).removeClass("active");
if ($(this).val() == "") {
$(this).addClass("backgroundtext");
$(this).addClass("invalid");
$(this).val($(this).prop("title"));
}else {
$(this).removeClass("invalid");
}
}
});
});
</script>
How it works…
页面工作原理如下:
-
When the form loads at runtime, all controls except the button controls are initialized by executing the
.each()method:$(":input[type!=submit]").each(function () {...});属性筛选器确保
type = submit的input元素,即按钮控件不包含在初始化中。 -
For each control on the form filtered using the preceding selector, if the control is empty, then the default text is displayed by setting the
ToolTiptext to its text value. The CSS class of the control is also set tobackgroundtext:if ($(this).val() == "") { $(this).addClass("backgroundtext"); $(this).val($(this).prop("title")); }注意事项
在运行时,ToolTip 作为
title属性呈现。 因此,$(this).prop("title")给出了工具提示文本。 -
For all the controls on the form, excluding the button controls, the
.on()method is used to bind event handlers to thefocusandblurevents, as follows:$(":input[type!=submit]").on({focus: function () {...}, blur: function () {...}});这里,绑定器分别用于将不同的事件处理程序附加到
focus和blur事件。 -
Now, let's discuss the individual event handlers, starting with the one for the focus event. When any control receives focus, we want the border color to change to blue, indicating that this is the current or active control. Also, if the control is empty, that is, if its text is set to the default value, then the default text should be cleared and any other styles should be removed. This can be achieved as follows:
focus: function () { $(this).addClass("active"); if ($(this).val() == $(this).prop("title")) { $(this).val(""); $(this).removeClass("backgroundtext"); $(this).removeClass("invalid"); } }在
blur的事件处理程序中,首先,由于控件不再是活动控件,相应的样式应该被删除。 其次,我们需要检查数据是否已经输入到控件中。 如果字段为空,其边框颜色将更改为红色。 此外,默认文本显示与相应的样式:blur: function () { $(this).removeClass("active"); if ($(this).val() == "") { $(this).addClass("backgroundtext"); $(this).addClass("invalid"); $(this).val($(this).prop("title")); }else { $(this).removeClass("invalid"); } }
参见 also
分离事件配方
使用事件委托将事件附加到未来的控件
这个配方演示了事件委派和事件冒泡。 通过在运行时添加元素,我们还将演示委托如何帮助您将事件附加到未来的控件。 本例中使用的构造如下:
|构造
|
类型
|
描述
|
| --- | --- | --- |
| $("html_tag") | jQuery 选择器 | 这将选择具有指定 HTML 标记的所有元素。 |
| .addClass() | jQuery 方法 | 这会将指定的 CSS 类添加到每个匹配的元素中。 |
| .append() | jQuery 方法 | 这将在每个匹配元素的末尾附加元素。 |
| [attribute= "value"] | jQuery 选择器 | 这将选择具有指定属性等于value字符串的元素。 |
| click | jQuery 的事件 | 当您单击一个元素时,它就会触发。 它对应于 JavaScript 的click事件。 |
| dblclick | jQuery 的事件 | 当您双击一个元素时就会触发。 它对应于 JavaScript 的dblclick事件。 |
| .on() | jQuery 事件绑定 | 这将一个或多个事件的事件处理程序附加到匹配的元素。 |
| .removeClass() | jQuery 方法 | 这将从每个匹配的元素中删除指定的 CSS 类。 |
准备
按照下面列出的步骤创建一个窗体来演示事件冒泡和委托:
-
We will create a simple web page that displays data rows from an XML file. A new data row is added at runtime so that we can see the impact with and without delegation:
![Getting ready]()
当您双击某一行的时,它将高亮显示,如下面的截图所示。 用鼠标单击同一行,高亮部分可以删除:
![Getting ready]()
-
要创建前面的页面,请启动新的ASP.NET Web 应用项目在 Visual Studio 中使用空模板,并将其命名为
Recipe4(或任何其他合适的名称)。 -
在项目中创建一个
Scripts文件夹,并将 jQuery 库文件添加到此文件夹中。 -
将
App_Data文件夹添加到项目中,在解决方案资源管理器选项卡中右键单击项目,并导航到添加|添加 ASP。 |App_Data。 -
右键单击
App_Data文件夹,转到添加|XML 文件。 在弹出的对话框中,将文件命名为StudentData.xml,然后单击OK按钮。 -
现在,在Solution Explorer选项卡中双击前面的 XML 文件以打开该文件。 输入一些学生记录样本,结构如下:
<StudentData> <Student> <ID>...</ID> <Name>...</Name> <Score>...</Score> <Module>...</Module> </Student> ... </StudentData> -
添加一个新的 web 表单到项目中,并在页面中包含 jQuery 库。
-
导航到工具箱|Data,将
XMLDataSource和Repeater控件添加到窗体中。 -
In the Design view of the web form, click on the small arrow icon in the top-right corner of the XMLDataSource option to open its configuration menu, as shown here:
![Getting ready]()
-
From the preceding menu, select Configure Data Source, go to the path of the
StudentData.xmlfile, and set its XPath to/StudentData/Student, as shown in the following screenshot. Click on the OK button:

- Now that the XMLDataSource option has been configured in the Design view, click on the small arrow in the top-right corner of the
Repeatercontrol to open the Repeater Tasks menu. Select the XMLDataSource option, that was configured earlier, from the Choose Data Source dropdown:

- 将以下标记添加到
Repeater控件中,以便它显示学生记录的字段:
```
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="XmlDataSource1">
<HeaderTemplate>
<table id="StudentData">
<thead>
<tr>
<th>ID</th>
<th>Student Name</th>
<th>Module</th>
<th>Score</th>
</tr>
</thead>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%# XPath("ID") %></td>
<td><%# XPath("Name") %></td>
<td><%# XPath("Module") %></td>
<td><%# XPath("Score") %></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
```
- 在页面的
head元素中包含以下样式。 该样式将应用于需要突出显示的行:
```
<style type="text/css">
.highlight{
background-color:greenyellow;
}
</style>
```
怎么做……
在网页的<script>块中包含以下 jQuery 代码:
<script type="text/javascript">
$(document).ready(function () {
$("table[id=StudentData] ").on("dblclick","tr", function () {
$(this).addClass("highlight");
});
$("table[id=StudentData] ").on("click", "tr", function () {
$(this).removeClass("highlight");
});
$("table[id=StudentData]").append("<tr><td>HT2015051</td><td>Abraham A.</td><td>ISR</td><td>70</td></tr>");
});
</script>
How it works…
页面工作原理如下:
-
用Ctrl+S保存页面,然后用F5运行。 页面加载后,
Repeater控件显示来自 XML 文件的学生数据。 -
不是将双击事件附加到表行,而是使用
.on()事件绑定器将事件处理程序附加到父表。 元素被指定为筛选允许触发事件的子代元素的选择器。 因此,当您双击一个表行时,事件气泡上升到父表,并执行相应的dblclick事件处理程序:$("table[id=StudentData] ").on("dblclick","tr", function () { $(this).addClass("highlight"); }); -
类似地,
click事件处理程序被附加到父表而不是tr元素。 通过单击任意一行,可以删除高亮显示:$("table[id=StudentData] ").on("click", "tr", function () { $(this).removeClass("highlight"); }); -
At runtime, a new table row can be appended using the
.append()function as follows:$("table[id=StudentData]").append("<tr><td>HT2015051</td><td>Abraham A.</td><td>ISR</td><td>70</td></tr>");这一行显示了与其他行的相同的行为; 也就是说,你可以双击它来添加一个背景颜色,然后点击它一次来删除背景颜色。
-
Now, to see the behavior of a dynamically added row in the absence of event delegation, modify the event bindings to attach the events to the table row instead of the parent table, as follows:
$("table[id=StudentData] tr").on("dblclick", function () { $(this).addClass("highlight"); }); $("table[id=StudentData] tr").on("click", function () { $(this).removeClass("highlight"); });现在,当在运行时添加新行时,它不会显示
click和dbclick事件上所需的行为。
参见 also
响应鼠标事件配方
只跑一次比赛
某些应用只需要触发一次事件处理程序。 如果使用.on()方法连接事件处理程序,则每次事件发生时都会触发该事件处理程序,这在这种情况下可能是不希望的。 本菜谱演示了如何附加一次性调用的事件处理程序。 本例中使用的结构总结如下:
构造
|
类型
|
描述
|
| --- | --- | --- |
| $(".class") | jQuery 选择器 | 它匹配指定 CSS 类的所有元素。 |
| $("html_tag") | jQuery 选择器 | 这将选择具有指定 HTML 标记的所有元素。 |
| [attribute= "value"] | jQuery 选择器 | 这将选择具有指定属性等于value字符串的元素。 |
| click | jQuery 的事件 | 当您单击一个元素时,它就会触发。 它对应于 JavaScript 的click事件。 |
| .hide() | jQuery 方法 | 这将隐藏匹配的元素。 |
| .one() | jQuery 事件绑定 | 这将一个或多个事件的事件处理程序附加到匹配的元素。 处理程序最多执行一次。 |
| .show() | jQuery 方法 | 这会显示匹配的元素。 |
准备
要创建只执行一次事件处理程序的表单,请遵循以下步骤:
-
We will build the web form, as shown in the following screenshot, to display the
Employeerecords from the Northwind database. The page has a See More... link to display additional details about the employee:![Getting ready]()
当您点击链接时,页面上会显示附加的详细信息,如下图所示:
![Getting ready]()
The见更多… 链接被设计为只工作一次。 后续单击该链接将不会触发任何事件处理程序。
提示
Northwind 是一个开源数据库,可以从https://northwinddatabase.codeplex.com下载。 从 MSDN 页面https://msdn.microsoft.com/en-us/library/8b6y4c7s.aspx了解更多关于如何安装示例数据库
-
为了构建前面的页面,我们需要创建一个ASP.NET Web 应用项目,并将其命名为
Recipe5(或其他合适的名称)。 -
向项目中添加一个
Scripts文件夹,并将 jQuery 库添加到该文件夹中。 -
向项目中添加一个新的 web 表单。 在表单中包含 jQuery 库。
-
以Design模式打开窗体。 转到工具箱|Data,在窗体中添加
SqlDataSource控件。 -
In the Design mode, click on the small arrow icon that appears in the top-right corner of the
SqlDataSourcecontrol onmouseover. Click on Configure Data Source, as shown here:![Getting ready]()
-
Follow the wizard, and add a new database connection. In the dialog box, enter your server name, select the Northwind catalog, and click on OK:
![Getting ready]()
注意事项
请注意,本书中所有数据库驱动的示例都使用 Windows 身份验证。 因此,在 MS SQL Server 中,给 windows 帐户访问 Northwind 数据库的权限是很重要的。
-
In the Configure the Select Statement dialog box, as shown in the following screenshot, choose Specify columns from a table or view from the radio button list, and select the
Employeestable from the drop-down menu. Check the columns required to be displayed on the page, such asEmployeeID,LastName,FirstName,Country,HomePhone, andNotes. Click on the Next button:![Getting ready]()
测试查询,并通过单击Finish按钮来完成向导。
-
Now, in the Design mode, drag and drop a
FormViewcontrol by navigating to Toolbox | Data. Click on the small arrow icon that appears in the top-right corner of theFormViewcontrol onmouseover, and click on Choose Data Source. SelectSqlDataSource1from the drop-down menu, as shown here:![Getting ready]()
-
在源模式中向
FormView控件添加以下标记:
```
<asp:FormView ID="FormView1" runat="server" AllowPaging="True" DataKeyNames="EmployeeID" DataSourceID="SqlDataSource1">
<ItemTemplate>
<table id="EmployeeData">
<tr>
<td>EmployeeID:</td>
<td><asp:Label ID="EmployeeIDLabel" runat="server" Text='<%# Eval("EmployeeID") %>' /></td>
</tr>
<tr>
<td>Last Name:</td>
<td><asp:Label ID="LastNameLabel" runat="server" Text='<%# Bind("LastName") %>' /></td>
</tr>
<tr>
<td>First Name:</td>
<td><asp:Label ID="FirstNameLabel" runat="server" Text='<%# Bind("FirstName") %>' /></td>
</tr>
<tr>
<td>Country:</td>
<td><asp:Label ID="CountryLabel" runat="server" Text='<%# Bind("Country") %>' /></td>
</tr>
<tr>
<td>Home Phone:</td>
<td><asp:Label ID="HomePhoneLabel" runat="server" Text='<%# Bind("HomePhone") %>' /></td></tr>
<tr>
<td colspan="2">
<asp:HyperLink ID="lnkMore" runat="server" CssClass="morelink">See More...</asp:HyperLink>
</td>
</tr>
</table>
<asp:Label ID="lblMoreData" CssClass="moredata" runat="server" Text='<%#Bind("Notes") %>'></asp:Label>
<br/>
</ItemTemplate>
</asp:FormView>
```
- Add the following styles to the
headelement of the page:
```
<style type="text/css">
.moredata{
color:grey;
}
.morelink{
cursor:pointer;
color:maroon;
text-decoration:underline;
}
</style>
```
CSS 类应用于页面上显示的员工的附加详细信息。 `morelink`CSS 类用于样式链接。
怎么做……
将下面的 jQuery 代码添加到页面的<script>块中:
<script type="text/javascript">
$(document).ready(function () {
$(".moredata").hide();
$("table[id=EmployeeData]").one("click", "a.morelink", function () {
$(".moredata").show();
});
});
</script>
How it works…
页面工作原理如下:
-
保存应用并使用F5运行它。 该页面从
Employees表加载第一条记录,并将其显示在FormView控件中。 可以使用页面底部的页码来浏览记录。 -
Each page displays the basic employee details, such as the name, country, and home phone number. The notes related to the employee are hidden using the following code:
$(".moredata").hide();前面的选择器使用分配给
FormView项模板中的lblMoreData标签控件的 CSS 类。 -
A See More... hyperlink provided in the FormView option enables you to view the notes related to the employee record. This is done using the
.one()event binder attached to the parent table:$("table[id=EmployeeData]").one("click", "a.morelink", function () { $(".moredata").show(); });使用
.one()而不是.on()可以最多调用一次事件处理程序。 一旦事件处理程序被执行,它将与元素分离,这样就不能重新调用它。请注意,事件处理程序被附加到父元素,而不是直接将其附加到超链接。 带有
morelinkCSS 类的anchor元素作为可以引发事件的子选择器传递。一旦触发
click事件,包含注释的label控件将使用.show()方法显示。
参见 also
通过事件传递数据并使用事件命名空间配方
以程序方式触发事件
这个配方演示了.trigger()方法以编程方式调用事件的用法。 本例中使用的构造如下:
构造
|
类型
|
描述
|
| --- | --- | --- |
| $(".class") | jQuery 选择器 | 它匹配指定 CSS 类的所有元素。 |
| $("html_tag") | jQuery 选择器 | 这将选择具有指定 HTML 标记的所有元素。 |
| $(this) | jQuery 对象 | 它引用当前 jQuery 对象。 |
| .attr("name")或.attr("name", "value") | jQuery 方法 | 这将返回一个字符串,其中包含第一个匹配元素所需的属性值。 它还可以用于将属性设置为所需的值。 |
| [attribute= "value"] | jQuery 选择器 | 这将选择具有指定属性等于value字符串的元素。 |
| click | jQuery 的事件 | 当您单击一个元素时,它就会触发。 它对应于 JavaScript 的click事件。 |
| dblclick | jQuery 的事件 | 当您双击一个元素时,它就会触发。 它对应于 JavaScript 的double-click事件。 |
| eval() | JavaScript 函数 | 这将执行 JavaScript 表达式。 |
| .find() | jQuery 方法 | 这将查找与过滤器匹配的所有元素。 |
| .on() | jQuery 事件绑定 | 这将一个或多个事件的事件处理程序附加到匹配的元素。 |
| .trigger() | jQuery 方法 | 这将执行附加到匹配元素的处理程序和行为。 |
准备
要创建一个以编程方式触发事件的网页,请遵循以下步骤:
-
We will build a web page, as shown in the following screenshot. The page displays the list of products from the Northwind database in a
GridViewcontrol. TheGridViewcontrol has an Edit column containing aLinkButtoncontrol to edit any particular row of data:![Getting ready]()
一般情况下,点击某一行的Edit链接时,记录进入编辑模式,显示Update和Cancel链接。 在本例中,当用户双击某一行时,我们将使用 jQuery 触发Edit链接的单击。 因此,通过编程方式激活特定行的编辑模式,如下图所示:
![Getting ready]()
-
要构建前面的页面,请创建一个ASP.NET Web 应用项目,并将其命名为
Recipe6(或任何其他合适的名称)。 -
向项目中添加一个
Scripts文件夹,并将 jQuery 库添加到该文件夹中。 -
向项目中添加一个新的 web 表单。 在 web 表单中包含 jQuery 库。
-
Now, right-click on the project in Solution Explorer, and go to Add | New Item. From the dialog box, select Data in the left-hand side panel and ADO.NET Entity Data Model in the middle panel. Enter the name
ProductModelin the text field shown in the following screenshot, and click on the Add button:![Getting ready]()
-
In the Entity Data Model Wizard, select EF Designer from database, and click on the Next button:
![Getting ready]()
-
Create a connection to the Northwind database running on MS SQL Server, and save the connection string in
web.configasNorthwindEntities. Click on the Next button:![Getting ready]()
-
On the next screen, which displays the database objects, check the Products table by navigating to Tables | dbo | Products, and click on the Finish button:
![Getting ready]()
-
现在,通过导航到工具箱|Data,将
GridView控件添加到 web 窗体。 -
In the code-behind file (
Default.aspx.vborDefault.aspx.cs), add the following method to retrieve records from the Products table.
对于 VB,代码如下:
```
Public Function GridView1_GetData() As IQueryable
Dim db As NorthwindEntities = New NorthwindEntities()
Dim queryResults = From prod In db.Products
Order By prod.ProductID
Select prod.ProductID, prod.ProductName, prod.UnitPrice, prod.UnitsInStock
Return queryResults
End Function
```
对于 c#,代码如下:
```
public IQueryable GridView1_GetData()
{
NorthwindEntities db = new NorthwindEntities();
var query = from prod in db.Products
orderby prod.ProductID
select new
ProductID = prod.ProductID,
ProductName = prod.ProductName,
UnitPrice = prod.UnitPrice,
UnitsInStock = prod.UnitsInStock
};
return query;
}
```
- 将
GridView的SelectMethod设置为GridView标记中的上述方法:
```
SelectMethod="GridView1_GetData"
```
- 为页面的
head元素中的GridView中的Edit链接定义一个 CSS 样式:
```
<style type="text/css">
.edit{
color:blue;
cursor:pointer;
}
</style>
```
- 页面的完整标记(不包括应用于
GridView的样式)如下:
怎么做……
将下面的 jQuery 代码添加到页面的<script>块中:
<script type="text/javascript">
$(document).ready(function () {
$("table[id=GridView1]").on("dblclick", "tr", function () {
$(this).find(".edit").trigger("click");
});
$(".edit").click(function () {
eval($(this).attr('href'));
});
});
</script>
How it works…
页面工作原理如下:
-
当您运行该页面时,产品列表显示在
GridView控件中。 -
现在,双击任意一行。 您将注意到,这将模拟单击该特定行的Edit链接。 这可以通过将一个事件处理程序附加到行元素的
dblclick事件,如下所示: -
事件处理程序使用
editCSS 类选择该行中的Edit链接,使用.trigger()方法调用此链接上的click事件,如下所示: -
Finally, an event handler is attached to the click event of the Edit link:
$(".edit").click(function () {...});这个事件处理程序使用 JavaScript 的
eval()函数调用附加在Edit链接上的href属性:eval($(this).attr('href'));
参见 also
使用事件委托将事件附加到未来控件配方
通过事件传递数据并使用事件命名空间
在这个配方中,我们将演示如何使用.trigger()方法传递事件数据。 事件数据将以JavaScript 对象表示法(JSON)格式定义,这只是名称/值对的集合。 我们还将了解如何在同一事件类型上使用名称空间来执行不同的处理程序。 本例中使用的构造如下:
构造
|
类型
|
描述
|
| --- | --- | --- |
| $(this) | jQuery 对象 | 它引用当前 jQuery 对象。 |
| :checked | jQuery 选择器 | 这将选择所有选中的复选框和单选按钮。 |
| click | jQuery 的事件 | 当您单击一个元素时,它就会触发。 它对应于 JavaScript 的click事件。 |
| .find() | jQuery 方法 | 这将查找匹配筛选器的所有元素。 |
| .on() | jQuery 事件绑定 | 这将一个或多个事件的事件处理程序附加到匹配的元素。 |
| .trigger() | jQuery 方法 | 这将执行附加到匹配元素的处理程序和行为。 |
| .val() | jQuery 方法 | 返回第一个匹配元素的值,或者设置每个匹配元素的值。 |
准备
要通过事件传递数据并使用事件命名空间,请遵循以下步骤:
-
We will create a simple web page with two
RadioButtonListcontrols and oneButtoncontrol as follows:![Getting ready]()
当您单击第一个
RadioButtonList控件中的任意单选按钮时,Button控件的click事件将以编程方式调用,并将所选单选按钮上的信息传递给事件处理程序。 事件数据显示在 JavaScript 警告消息中,如下截图所示:![Getting ready]()
当您单击第二个
RadioButtonList控件中的任意单选按钮时,将再次以编程方式调用Button控件的click事件处理程序,并传递事件数据。 然而,这一次执行了不同的处理程序,事件数据显示在 JavaScript 的确认框中,如下所示:![Getting ready]()
-
首先,创建一个ASP.NET Web 应用项目,并将其命名为
Recipe7(或任何其他合适的名称)。 -
向项目中添加一个
Scripts文件夹,并将 jQuery 库添加到该文件夹中。 -
向项目中添加一个新的 web 表单。 在表单中包含 jQuery 库。
-
在页面中添加以下标记:
<table> <tr> <td><fieldset> <asp:RadioButtonList ID="RadioButtonList1" runat="server" Width="120px"> <asp:ListItem Text="Type 1" Value="1"></asp:ListItem> <asp:ListItem Text="Type 2" Value="2"></asp:ListItem> </asp:RadioButtonList> </fieldset></td> <td><fieldset> <asp:RadioButtonList ID="RadioButtonList2" runat="server" Width="120px"> <asp:ListItem Text="Type 3" Value="3"></asp:ListItem> <asp:ListItem Text="Type 4" Value="4"></asp:ListItem> </asp:RadioButtonList> </fieldset></td> </tr> </table><br /> <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
怎么做……
在页面的<script>块中包含以下 jQuery 代码:
<script type="text/javascript">
$(document).ready(function () {
$("#<%=RadioButtonList1.ClientID%>").on("click", function () {
var strValContent = $(this).find(":checked").val();
var data = { txtContent: "Group 1", valContent: strValContent };
$("#<%=btnSubmit.ClientID%>").trigger("click.radioclick1", data);
});
$("#<%=RadioButtonList2.ClientID%>").on("click", function () {
var strValContent = $(this).find(":checked").val();
var data = { txtContent: "Group 2", valContent: strValContent };
$("#<%=btnSubmit.ClientID%>").trigger("click.radioclick2", data);
});
$("#<%=btnSubmit.ClientID%>").on("click.radioclick1", function (evt,data) {
if (data != null){
var strMessage = "You have selected the following: \r\n"+
"Event Group: " + data.txtContent + "\r\n" +
"Type: " + data.valContent ;
alert(strMessage);
}
});
$("#<%=btnSubmit.ClientID%>").on("click.radioclick2", function (evt, data) {
if (data != null){
var strMessage = "You have selected the following: \r\n" +
"Event Group: " + data.txtContent + "\r\n" +
"Type: " + data.valContent;
window.confirm(strMessage);
}
});
});
</script>
How it works…
-
当页面加载时,当您单击第一个
RadioButtonList控件中的任意单选按钮时,其click事件对应的事件处理程序将被执行:$("#<%=RadioButtonList1.ClientID%>").on("click", function () {...}); -
The preceding event handler first reads the selected value of the radio button:
var strValContent = $(this).find(":checked").val();然后形成一个 JSON 字符串,将前面的值作为事件数据传递:
var data = { txtContent: "Group 1", valContent: strValContent };最后,它用所需的
click.radioclick1命名空间触发Button控件的click事件,并传递所需的事件数据:$("#<%=btnSubmit.ClientID%>").trigger("click.radioclick1", data); -
When the
clickevent is invoked programmatically, its corresponding event handler with theclick.radioclick1namespace is executed:$("#<%=btnSubmit.ClientID%>").on("click.radioclick1", function (evt,data) {...});这个处理程序读取事件数据。 如果数据不为空,则在警告消息中显示如下:
if (data != null){ var strMessage = "You have selected the following: \r\n"+ "Event Group: " + data.txtContent + "\r\n" + "Type: " + data.valContent ; alert(strMessage); } -
类似地,当您单击第二个
RadioButtonList控件中的单选按钮时,将执行其click事件对应的事件处理程序:$("#<%=RadioButtonList2.ClientID%>").on("click", function ( ) {...}); -
The preceding event handler first reads the selected value of the radio button:
var strValContent = $(this).find(":checked").val();然后形成一个 JSON 字符串作为事件数据传递:
var data = { txtContent: "Group 2", valContent: strValContent };最后,它用所需的
click.radioclick2命名空间触发Button控件的click事件,并传递所需的事件数据:$("#<%=btnSubmit.ClientID%>").trigger("click.radioclick2", data); -
When the
clickbutton is invoked programmatically, this time, the event handler with theclick.radioclick2namespace is executed:$("#<%=btnSubmit.ClientID%>").on("click.radioclick2", function (evt,data) {...});这个处理程序读取事件数据。 如果数据不是
null,则会在confirm消息中显示如下信息:if (data != null){ var strMessage = "You have selected the following: \r\n" + "Event Group: " + data.txtContent + "\r\n" + "Type: " + data.valContent; window.confirm(strMessage); }
参见 also
以编程方式触发事件
分离事件
这个配方演示了.off()方法的使用,以从页面元素分离事件处理程序。 本例中使用的构造如下:
构造
|
类型
|
描述
|
| --- | --- | --- |
| $("html_tag") | jQuery 选择器 | 这将选择具有指定 HTML 标记的所有元素。 |
| $(this) | jQuery 对象 | 它引用当前 jQuery 对象。 |
| .addClass() | jQuery 方法 | 这会将指定的 CSS 类添加到每个匹配的元素中。 |
| blur | jQuery 的事件 | 当一个元素失去焦点时触发。 它对应于 JavaScript 的blur事件。 |
| :checked | jQuery 选择器 | 这将选择所有选中的复选框和单选按钮。 |
| click | jQuery 的事件 | 当您单击一个元素时,它就会触发。 它对应于 JavaScript 的click事件。 |
| focus | jQuery 的事件 | 当元素接收到焦点时触发。 它对应于 JavaScript 的focus事件。 |
| :input | jQuery 选择器 | 它匹配input、button、select和textarea元素。 |
| .is() | jQuery 方法 | 如果匹配的元素满足给定条件,则返回一个布尔值。 |
| .off() | jQuery 方法 | 这将从匹配的元素中删除事件处理程序。 |
| .on() | jQuery 事件绑定 | 这将一个或多个事件的事件处理程序附加到匹配的元素。 |
| .removeClass() | jQuery 方法 | 这将从每个匹配的元素中删除指定的 CSS 类。 |
准备
要创建一个窗体来演示事件的分离,请遵循以下步骤:
-
Create the following sample page consisting of a few
TextBoxcontrols. There is aCheckBoxcontrol on the top of the page. When theCheckBoxcontrol is checked, the current control withfocusis highlighted with a blue border, as shown in the following screenshot:![Getting ready]()
当
CheckBox控件未选中时,主动控件不再像在前一种情况中那样用蓝色边框突出显示:![Getting ready]()
-
要构建前面的页面,请创建ASP.NET Web 应用项目,并将其命名为
Recipe8(或其他合适的名称)。 -
向项目中添加一个
Scripts文件夹,并将 jQuery 库添加到该文件夹中。 -
向项目中添加一个新的 web 表单。 在表单中包含 jQuery 库。
-
将以下标记添加到页面:
<table> <tr> <td colspan="2"><asp:CheckBox ID="chkHighlight" runat="server" Text="Highlight TextBoxes" /> </td> </tr> <tr> <td colspan="2"><asp:Label ID="lblName" runat="server" Text="Name"></asp:Label> </td> </tr> <tr> <td><asp:TextBox ID="txtFirst" runat="server"></asp:TextBox> </td> <td><asp:TextBox ID="txtLast" runat="server"></asp:TextBox> </td> </tr> <tr> <td colspan="2"><asp:Label ID="lblEmail" runat="server" Text="Email"></asp:Label> </td> </tr> <tr> <td colspan="2"><asp:TextBox ID="txtEmail" runat="server"></asp:TextBox> </td> </tr> <tr> <td colspan="2"><asp:Label ID="lblHomeAddr" runat="server" Text="Home Address"></asp:Label> </td> </tr> <tr> <td colspan="2"><asp:TextBox ID="txtHomeAddr" runat="server"></asp:TextBox> </td> </tr> <tr> <td colspan="2"><asp:Label ID="lblMailingAddr" runat="server" Text="Mailing Address"></asp:Label> </td> </tr> <tr> <td colspan="2"><asp:TextBox ID="txtMailingAddr" runat="server"></asp:TextBox> </td> </tr> <tr> <td colspan="2"></td> </tr> <tr> <td colspan="2"> <asp:Button ID="btnSubmit" runat="server" Text="Submit" /> <asp:Button ID="btnReset" runat="server" Text="Reset" /> </td> </tr> </table> -
向
head元素添加以下样式,为活动元素添加蓝色边框:
怎么做……
在页面的<script>块中包含以下 jQuery 代码:
<script type="text/javascript">
$(document).ready(function () {
$("#<%=chkHighlight.ClientID%>").on("click", function () {
if ($(this).is(":checked")) {
$("input:text").on("focus", function () {
$(this).addClass("active");
});
$("input:text").on("blur", function () {
$(this).removeClass("active");
});
} else {
$("input:text").off();
}
});
});
</script>
How it works…
页面工作原理如下:
-
通过按F5键运行应用。 当页面加载时,复选框控件未选中。 通过勾选复选框控件,它的
click事件处理程序将被执行: -
事件处理程序首先检查控件是否被选中。 如果选中该选项,它将向窗体上的
focus和blur事件的所有TextBox控件中添加事件处理程序。 在focus事件处理程序中,TextBox控件被高亮显示,在blur中,高亮显示被删除,如下所示: -
如果
CheckBox控件未选中,则使用.off()方法删除与TextBox控件关联的所有事件处理程序,如下所示:else { $("input:text").off(); }
参见 also
只运行一次事件配方
四、ASP.NET 中的 DOM 遍历和操作
本章将介绍用于遍历 DOM 树的方法以及可用于操作这些方法的技术。 我们将在本章中讨论以下配方:
- 添加/移除 DOM 元素
- 访问父控件和子控件
- 访问兄弟控制
- 使用过滤器细化选择
- 在运行时向控件添加项
简介
文档对象模型(DOM)为 web 页面提供了一种树状格式的结构化文档的表示。 树中的每个节点都绑定到属性、方法和事件处理程序。 web 页面本身被称为document对象,可以使用window.document从window对象访问。 页面上的 HTML 元素成为元素节点,比如head元素或body元素。 这些节点又可以有子节点,如table、div、input等等。 有些节点可能是文本节点,而有些节点也可能是注释节点。
需要注意的是,DOM 不是一种编程语言,而是一种可跨各种语言(如 JavaScript、HTML 和 XML)使用的面向对象模型。 因此,它是语言独立的,并且提供了一个通用的应用编程接口(API),可以由各种语言实现。 通过将网页连接到编程语言,你可以操纵它们的样式、结构和内容。
jQuery 提供了许多遍历 DOM 树的方法,比如访问父元素、子元素、兄弟元素或下一个/前一个元素。 使用 jQuery,可以在运行时使用客户机代码添加、删除或克隆 DOM 元素。 在本章中,我们将看到这是如何实现的。
添加/删除 DOM 元素
这个食谱演示了如何在 DOM 上克隆元素。 我们还将看到如何从 DOM 树中完全删除元素。 本例中使用的编程结构总结于下表:
|构造
|
类型
|
描述
|
| --- | --- | --- |
| $("#identifier") | jQuery 选择器 | 这将根据元素的 ID 选择一个元素 |
| $("html_tag") | jQuery 选择器 | 这将选择具有指定 HTML 标记的所有元素。 |
| .addClass() | jQuery 方法 | 这会将指定的CSS类添加到每个匹配的元素中。 |
| .attr("name")或.attr("name", "value") | jQuery 方法 | 这将返回一个字符串,其中包含第一个匹配元素所需的属性值。 它还可以用于将属性设置为所需的值。 |
| [attribute= "value"] | jQuery 选择器 | 这将选择具有指定属性等于"value"字符串的元素。 |
| .appendTo() | jQuery 方法 | 这将在目标的末尾插入元素。 |
| click | jQuery 的事件 | 当您单击一个元素时,它就会触发。 它对应于 JavaScript 的click事件。 |
| .clone() | jQuery 方法 | 这将对匹配的元素进行深度复制,也就是说,将复制匹配的元素及其子代和文本节点。 |
| event.preventDefault() | jQuery 方法 | 这将防止触发事件的默认动作。 |
| .find() | jQuery 方法 | 这将查找与筛选器匹配的所有元素。 |
| .length | jQuery 的财产 | 这将返回 jQuery 对象中的元素数量。 |
| .on() | jQuery 事件绑定 | 这将一个或多个事件的事件处理程序附加到匹配的元素。 |
| .remove() | jQuery 方法 | 这将从文档中删除匹配的元素及其后代元素。 所有相关的数据和事件也将被删除。 |
| .removeClass() | jQuery 方法 | 这将从每个匹配的元素中移除指定的 CSS 类。 |
| .val() | jQuery 方法 | 返回第一个匹配元素的值,或者设置每个匹配元素的值。 |
准备
按照的步骤创建一个页面来显示添加和移除 DOM 元素:
-
In this recipe, let's create a subsection of a job application form where the applicant needs to key in the current and past working experience. Since this is a variable section and different applicants can have different number of job experiences, we will let the user add new subsections if required. Once the page is loaded, the following form will be displayed:
![Getting ready]()
-
When you click on the Add Work Experience link, a new subsection is added as follows:
![Getting ready]()
-
When you click on the Remove Work Experience link, a prompt message is displayed to the user, as shown in the following screenshot:
![Getting ready]()
通过单击取消,取消该操作。 通过点击OK,前一个小节将从表单中永久删除。
-
首先,创建一个新的ASP.NET Web 应用项目在 Visual Studio 中使用空模板,并将其命名为
Recipe1(或任何其他合适的名称)。 -
在项目中添加一个
Scripts文件夹,并将 jQuery 库文件包含在该文件夹中。 -
添加一个新 web 表单,并在此表单中包含 jQuery 库。
-
添加两个表单字段:
Company Name和Designation到表单中。 在这些字段下面拖放两个LinkButton控件:一个用于添加新的部分,另一个用于删除前面的部分。 另外,为窗体添加两个 Button 控件,分别用于Submit和Reset功能。 因此,表单的标记如下:<div id="container"> <asp:Panel ID="pnlWorkExp" runat="server" CssClass="addPanel"> <table> <tr> <td> <asp:Label ID="lblCompany" runat="server" Text="Company Name:"></asp:Label> </td> <td> <asp:TextBox ID="txtCompany" runat="server"></asp:TextBox> </td> </tr> <tr> <td> <asp:Label ID="lblDesignation" runat="server" Text="Designation:"></asp:Label> </td> <td> <asp:TextBox ID="txtDesignation" runat="server"></asp:TextBox> </td> </tr> </table> </asp:Panel> </div> <asp:LinkButton ID="lnkAddWorkExp" runat="server">Add Work Experience</asp:LinkButton> <asp:LinkButton ID="lnkRemWorkExp" runat="server">Remove Work Experience</asp:LinkButton> <br /><br /> <asp:Button ID="btnSubmit" runat="server" Text="Submit" /> <asp:Button ID="btnReset" runat="server" Text="Reset" /> -
注意表单有一个容器 div 区域,由
Panel控件的组成。 我们将克隆这个Panel每次点击添加工作经验链接。 添加以下样式到这个Panel: -
我们还将在页面上的
disabled控件中添加样式:.disabled{ color:gray; text-decoration:none; }
怎么做……
在窗体中添加以下 jQuery 代码到<script>块:
<script type="text/javascript">
$(document).ready(function() {
$("#<%=lnkRemWorkExp.ClientID%>").attr("disabled", true).addClass("disabled");
$("#<%=lnkAddWorkExp.ClientID%>").on("click", function(evt) {
evt.preventDefault();
var cnt = $(".addPanel").length + 1;
var clone = $("#<%=pnlWorkExp.ClientID%>").clone();
clone.attr("ID", "<%=pnlWorkExp.ClientID%>_" + cnt);
clone.find("#<%=lblCompany.ClientID%>").attr("ID", "<%=lblCompany.ClientID%>_" + cnt);
clone.find("#<%=txtCompany.ClientID%>").attr("ID", "<%=txtCompany.ClientID%>_" + cnt).attr("name", "<%=txtCompany.ClientID%>_" + cnt).val("");
clone.find("#<%=lblDesignation.ClientID%>").attr("ID", "<%=lblDesignation.ClientID%>_" + cnt);
clone.find("#<%=txtDesignation.ClientID%>").attr("ID", "<%=txtDesignation.ClientID%>_" + cnt).attr("name", "<%=txtDesignation.ClientID%>_" + cnt).val("");
clone.appendTo("#container");
$("#<%=lnkRemWorkExp.ClientID%>").attr("disabled", false).removeClass("disabled");
});
$("#<%=lnkRemWorkExp.ClientID%>").on("click", function(evt) {
evt.preventDefault();
var cnt = $(".addPanel").length;
if (cnt > 1) {
if (confirm("Are you sure you want to remove the above section?")) {
$("#<%=pnlWorkExp.ClientID%>_" + cnt).remove();
cnt--;
if (cnt == 1)
$("#<%=lnkRemWorkExp.ClientID%>").attr("disabled", false).addClass("disabled");
}
}
});
$("#<%=btnSubmit.ClientID%>").on("click", function(evt) {
evt.preventDefault();
//handle form submission using AJAX here
});
$("#<%=btnReset.ClientID%>").on("click", function(evt) {
evt.preventDefault();
$("input[type=text]").val("");
});
});
</script>
How it works…
让我们看看如何添加和删除 DOM 元素:
-
In the jQuery code, the Remove Work Experience link is initially disabled by setting its
disabledattribute totrueas follows:$("#<%=lnkRemWorkExp.ClientID%>").attr("disabled", true).addClass("disabled");因此,最初在页面加载时,链接是不可点击的。
-
事件处理程序附加到
LinkButton控件以添加和删除子部分,以及Button控件以提交和重置表单:$("#<%=lnkAddWorkExp.ClientID%>").on("click", function (evt) {…}); $("#<%=lnkRemWorkExp.ClientID%>").on("click", function (evt) {…}); $("#<%=btnSubmit.ClientID%>").on("click", function (evt) {…}); $("#<%=btnReset.ClientID%>").on("click", function (evt) {…}); -
In the event handler of the Add Work Experience link, we are going to make a deep copy of the
Panelcontrol using the.clone()function. We will need to update theID,name, andvalueof each child control to avoid duplicates on the page. To get started with this, first prevent posting of the form due to the buttonclickaction:evt.preventDefault();因为我们需要为每个元素设置唯一的
ID,所以让我们将每个克隆元素的ID设置为OriginalID_N,其中OriginalID等于被克隆元素的ID。N等于原始元素的第 n 个实例。要确定
N的值,首先确定表单上具有addPanelCSS 类的Panel控件的总数。 将该计数增加1以获得下一个实例的数目,如下所示:var cnt = $(".addPanel").length + 1;复制原始
Panel控件:var clone = $("#<%=pnlWorkExp.ClientID%>").clone();将克隆
Panel的ID更新为OriginalID_N:clone.attr("ID", "<%=pnlWorkExp.ClientID%>_" + cnt);现在,开始将其子元素的
ID和name更新为OriginalID_N。 如果在控件中输入了任何数据,也将复制该数据。 因此,重置克隆文本控件的数据,如下所示:clone.find("#<%=lblCompany.ClientID%>").attr("ID", "<%=lblCompany.ClientID%>_" + cnt); clone.find("#<%=txtCompany.ClientID%>").attr("ID", "<%=txtCompany.ClientID%>_" + cnt).attr("name", "<%=txtCompany.ClientID%>_" + cnt).val(""); clone.find("#<%=lblDesignation.ClientID%>").attr("ID", "<%=lblDesignation.ClientID%>_" + cnt); clone.find("#<%=txtDesignation.ClientID%>").attr("ID", "<%=txtDesignation.ClientID%>_" + cnt).attr("name", "<%=txtDesignation.ClientID%>_" + cnt).val("");现在,克隆的 Panel 已经准备好被添加到容器 div 区域:
clone.appendTo("#container");通过将其
disabled属性更新为false来启用移除工作经验链接:$("#<%=lnkRemWorkExp.ClientID%>").attr("disabled", false).removeClass("disabled"); -
When you click on the Remove Work Experience link, we will remove the most recently added
Panelfrom the form. To do this, first prevent posting of the form on theclickevent:evt.preventDefault();获取表格上最后添加的
Panel编号,如下:var cnt = $(".addPanel").length;如果面板是原始元素,即表单上的第一个面板,它将不会被删除。 如果表单上有多个 Panel 控件,我们需要向用户显示确认对话框。 用户可以通过点击取消来关闭对话框。 如果用户单击OK,我们使用
.remove()函数删除 Panel 及其子元素。由于 Panels 的数量减少了
1,我们可以减少1的数量。 如果只剩下一个面板,禁用remove链接,避免移除原来的面板:if (cnt > 1) { if (confirm("Are you sure you want to remove the above section?")){ $("#<%=pnlWorkExp.ClientID%>_" + cnt).remove(); cnt--; if (cnt == 1) $("#<%=lnkRemWorkExp.ClientID%>").attr("disabled", false).addClass("disabled"); } }注意事项
由于 DOM 元素是使用客户机代码添加的,所以服务器端无法访问这些元素。 因此,在Submit按钮的事件处理程序中,检索所有 DOM 元素的内容并使用AJAX将其发布到服务器。 在第 9 章的序列化表单数据配方中,有用的 jQuery 配方为 ASP.NET Sites,网址:https://www.packtpub.com/sites/default/files/downloads/4836OT_Chapter_09。
-
在Reset按钮的事件处理程序中,阻止提交表单,并将所有文本控件的值重置如下:
evt.preventDefault(); $("input[type=text]").val("");
参见 also
访问同级控件配方
访问父控件和子控件
这个配方演示了在对示例表单执行客户端验证时,如何访问 DOM 中的父元素和子元素。 本例中使用的结构总结如下:
|构造
|
类型
|
描述
|
| --- | --- | --- |
| $("#identifier") | jQuery 选择器 | 这将基于其ID选择一个元素。 |
| $("html_tag") | jQuery 选择器 | 这将选择具有指定 HTML 标记的所有元素 |
| $(this) | jQuery 对象 | 它引用当前 jQuery 对象 |
| .addClass() | jQuery 方法 | 这会将指定的CSS类添加到每个匹配的元素中 |
| :checked | jQuery 选择器 | 这将选择选中的输入元素 |
| .children() | jQuery 方法 | 这会返回匹配元素的直接后代元素 |
| .each() | jQuery 方法 | 这将遍历匹配的元素,并为每个元素执行一个函数 |
| event.preventDefault() | jQuery 方法 | 这将防止触发事件的默认动作 |
| .find() | jQuery 方法 | 这将查找与筛选器匹配的所有元素 |
| .length | jQuery 的财产 | 这将返回 jQuery 对象中的元素数量 |
| .parent() | jQuery 方法 | 这将返回匹配元素的直接父元素 |
| .prop(propertyName)或.prop(propertyName, value) | jQuery 方法 | 这会为第一个匹配的元素返回指定属性的值,或者为所有匹配的元素设置指定属性的值 |
| .removeClass() | jQuery 方法 | 这将从每个匹配的元素中删除指定的 CSS 类 |
| :selected | jQuery 选择器 | 这将检索选定的输入元素 |
| .val() | jQuery 方法 | 返回第一个匹配元素的值,或者设置每个匹配元素的值 |
准备
下面是创建一个页面来演示访问父控件和子控件的步骤:
-
We will be validating a form that registers interested volunteers with the school museum. The form consists of the following fields:
![Getting ready]()
当您点击提交按钮时,按照以下规则对字段进行验证:
- 所有的字段都是强制性的,也就是说,它们应该是非空的
- 可用性字段应该至少选择了三个条目
未通过验证的字段将用红色高亮显示,如下所示:
![Getting ready]()
-
为了创建这个表单,启动一个新的ASP.NET Web 应用在 Visual Studio 中使用空的模板并将其命名为
Recipe2(或其他合适的名称)。 -
添加一个
Scripts文件夹,并将 jQuery 库包含在此文件夹中。 -
创建一个 web 表单,并在表单中包含 jQuery 库。
-
将以下标记添加到页面:
<table id="container"> <tr><td> <asp:Label ID="lblSalutation" runat="server" Text="Salutation:"></asp:Label></td> <td><asp:DropDownList ID="ddlSalutation" runat="server"> <asp:ListItem Text="---Please Select---" Value=""></asp:ListItem> <asp:ListItem Text="Mr" Value="Mr"></asp:ListItem> <asp:ListItem Text="Ms" Value="Ms"></asp:ListItem> <asp:ListItem Text="Mrs" Value="Mrs"></asp:ListItem> <asp:ListItem Text="Dr" Value="Dr"></asp:ListItem> <asp:ListItem Text="Prof" Value="Prof"></asp:ListItem> </asp:DropDownList> </td> </tr> <tr> <td> <asp:Label ID="lblName" runat="server" Text="Name:"></asp:Label> </td> <td> <asp:TextBox ID="txtName" runat="server"></asp:TextBox> </td> </tr> <tr> <td> <asp:Label ID="lblAffiliation" runat="server" Text="Type of Affiliation:"></asp:Label> </td> <td> <asp:RadioButtonList ID="rdlAffiliation" runat="server"> <asp:ListItem Text="Staff" Value="Staff"></asp:ListItem> <asp:ListItem Text="Student" Value="Student"></asp:ListItem> <asp:ListItem Text="Alumni" Value="Alumni"></asp:ListItem> </asp:RadioButtonList> </td> </tr> <tr> <td> <asp:Label ID="lblLanguages" runat="server" Text="Spoken Languages:"></asp:Label> </td> <td> <asp:CheckBoxList ID="chkLanguages" runat="server"> <asp:ListItem Text="English" Value="English"></asp:ListItem> <asp:ListItem Text="Chinese" Value="Chinese"></asp:ListItem> <asp:ListItem Text="Malay" Value="Malay"></asp:ListItem> <asp:ListItem Text="Tamil" Value="Tamil"></asp:ListItem> </asp:CheckBoxList> </td> </tr> <tr> <td> <asp:Label ID="lblAvailability" runat="server" Text="Availability (Select any 3):"></asp:Label> </td> <td> <asp:ListBox ID="lstAvailability" runat="server" SelectionMode="Multiple" Width="100%" Height="82px" > <asp:ListItem Text="Weekdays AM" Value="WeekdaysAM"></asp:ListItem> <asp:ListItem Text="Weekdays PM" Value="WeekdaysPM"></asp:ListItem> <asp:ListItem Text="Weekend AM" Value="WeekendAM"></asp:ListItem> <asp:ListItem Text="Weekend PM" Value="WeekendPM"></asp:ListItem> <asp:ListItem Text="Public Holidays" Value="PublicHolidays"></asp:ListItem> </asp:ListBox> </td> </tr> <tr> <td colspan="2"> <asp:Button ID="btnSubmit" runat="server" Text="Submit" /> <asp:Button ID="btnReset" runat="server" Text="Reset" /> </td> </tr> </table> -
要显示无效控件的边框和背景色,请包含以下样式:
.error{ border-style:solid; border-color:red; background-color:lightpink; } -
在
container表中添加以下样式,以便在两个控件之间提供足够的padding:#container{ padding:10px; }
怎么做……
将下面的 jQuery 代码添加到窗体的<script>块中:
<script type="text/javascript">
$(document).ready(function() {
$("#<%=btnSubmit.ClientID%>").click(function(evt) {
evt.preventDefault();
//Salutation field
if ($("#<%=ddlSalutation.ClientID%>").val() == "") $("#<%=ddlSalutation.ClientID%>").parent().addClass("error");
else $("#<%=ddlSalutation.ClientID%>").parent().removeClass("error");
//Name field
if ($("#<%=txtName.ClientID%>").val() == "")
$("#<%=txtName.ClientID%>").parent().addClass("error");
else
$("#<%=txtName.ClientID%>").parent().removeClass("error");
//Affiliation field
var rdlAffCount = $("#<%=rdlAffiliation.ClientID%>").find("input:checked").length;
if (rdlAffCount == 0) $("#<%=rdlAffiliation.ClientID%>").parent().addClass("error");
else $("#<%=rdlAffiliation.ClientID%>").parent().removeClass("error");
//Languages field
var chkLanguagesCount = $("#<%=chkLanguages.ClientID%>").find("input:checked").length;
if (chkLanguagesCount == 0) $("#<%=chkLanguages.ClientID%>").parent().addClass("error");
else $("#<%=chkLanguages.ClientID%>").parent().removeClass("error");
//Availability field
var lstAvailCount = $("#<%=lstAvailability.ClientID%>").children("option:selected").length;
if (lstAvailCount != 3) $("#<%=lstAvailability.ClientID%>").parent().addClass("error");
else $("#<%=lstAvailability.ClientID%>").parent().removeClass("error");
});
$("#<%=btnReset.ClientID%>").click(function(evt) {
evt.preventDefault();
//Salutation field
$("#<%=ddlSalutation.ClientID%>").val("");
$("#<%=ddlSalutation.ClientID%>").parent().removeClass("error");
//Name field
$("#<%=txtName.ClientID%>").val("");
$("#<%=txtName.ClientID%>").parent().removeClass("error");
//Affiliation field
$("#<%=rdlAffiliation.ClientID%> input").each(function() {
$(this).prop("checked", false);
});
$("#<%=rdlAffiliation.ClientID%>").parent().removeClass("error");
//Languages field
$("#<%=chkLanguages.ClientID%> input").each(function() {
$(this).prop("checked", false);
});
$("#<%=chkLanguages.ClientID%>").parent().removeClass("error");
//Availability field
$("#<%=lstAvailability.ClientID%> option").each(function() {
$(this).prop("selected", false);
});
$("#<%=lstAvailability.ClientID%>").parent().removeClass("error");
});
});
</script>
How it works…
让我们看看如何访问父控件和子控件:
-
当您点击提交按钮时,页面将被阻止发送回服务器:
evt.preventDefault(); -
接下来,从第一个控件
DropDownList开始,一步一步地验证字段。 如果该控件中没有选择任何选项,则需要将其标记为无效。 为此,获取它的parent元素——即表格单元格容器,并通过添加errorCSS 样式突出显示它。 但是,如果该字段不是空的,那么应该从parent表格单元格中删除任何高亮显示:if ($("#<%=ddlSalutation.ClientID%>").val() == "") $("#<%=ddlSalutation.ClientID%>").parent().addClass("error" ); else $("#<%=ddlSalutation.ClientID%>").parent().removeClass("err or"); -
接下来,验证文本框字段。 如果字段为空,则获取其
parent元素——即容器表单元格,并向其添加errorCSS 样式。 如果该字段不是空的,移除任何附加到它的高亮显示:if ($("#<%=txtName.ClientID%>").val() == "") $("#<%=txtName.ClientID%>").parent().addClass("error"); else $("#<%=txtName.ClientID%>").parent().removeClass("error"); -
The third field on the form is the
Affiliationfield, which is defined as aRadioButtonListcontrol. To determine whether any radio button is selected, we use the:checkedselector:var rdlAffCount = $("#<%=rdlAffiliation.ClientID%>").find("input:checked").le ngth;注意,在运行时,
RadioButtonList控件作为表元素呈现,而每个ListItem控件作为输入元素呈现,type = radio作为表行元素呈现,如下面的 HTML 源代码所示:![How it works…]()
因此,我们使用
.find()函数搜索表的子代,以找到所需的输入元素。如果没有选择选项,将突出显示
parent表单元格,表明它是一个无效字段。 否则,任何附加到单元格的高亮显示都可以删除:if (rdlAffCount == 0) $("#<%=rdlAffiliation.ClientID%>").parent().addClass("error "); else $("#<%=rdlAffiliation.ClientID%>").parent().removeClass("er ror"); -
Next, we will validate the Spoken Languages field, which is defined as a
CheckBoxListcontrol. At runtime, theCheckBoxListcontrol is rendered as a table element, and eachListItemcontrol is rendered as an input element withtype = checkboxin a table row element, as shown in the following HTML source:![How it works…]()
因此,我们再次使用
.find()函数搜索表的所有子代,以确定输入元素,如下所示:var chkLanguagesCount = $("#<%=chkLanguages.ClientID%>").find("input:checked").length;如果没有选中复选框,则将字段标记为无效; 否则,标记为有效,如下所示:
if (chkLanguagesCount == 0) $("#<%=chkLanguages.ClientID%>").parent().addClass("error"); else$("#<%=chkLanguages.ClientID%>").parent().removeClass("error"); -
Lastly, we check the Availability field, which is defined as a
ListBoxcontrol. Here, the condition for a successful validation is that at least three entries should be selected. So, first find out the total number of selected choices by filtering the options using the:selectedselector:var lstAvailCount = $("#<%=lstAvailability.ClientID%>").children("option:select ed").length;注意,在运行时,
ListBox控件作为select元素呈现,而每个ListItem控件作为option元素呈现,如下所示:![How it works…]()
使用
.children()函数是因为option元素是select元素的直接后代,我们不需要遍历所有后代。如果所选选项的数量不等于
3,则将该字段标记为无效; 否则,标记为有效如下:if (lstAvailCount != 3)$("#<%=lstAvailability.ClientID%>").parent().addClass("error"); else$("#<%=lstAvailability.ClientID%>").parent().removeClass("e rror"); -
当您点击Reset按钮时,我们需要清除输入到表单字段中的数据(如果有的话)。 同时,附加到任何表单元格的
errorCSS 类也应该被删除。 -
当点击Reset按钮时,首先阻止表单发送到服务器:
evt.preventDefault(); -
接下来,重置第一个
DropDownList字段的值,并删除附加到它的任何错误样式:$("#<%=ddlSalutation.ClientID%>").val(""); $("#<%=ddlSalutation.ClientID%>").parent().removeClass("error"); -
接下来,对
TextBox字段重复相同的过程:
```
$("#<%=txtName.ClientID%>").val(""); $("#<%=txtName.ClientID%>").parent().removeClass("error");
```
- 对于
RadioButtonList、CheckBoxList和ListBox控件,循环遍历每个选项并重置选择(如果有的话)。 此外,删除错误样式(如果有):
参见 also
添加/删除 DOM 元素配方
访问同级控件
在前面的配方中,我们从 DOM 树中的一个元素向上和向下遍历。 在这个配方中,让我们遍历同一级别上的其他控件。 本例中使用的结构总结如下:
|构造
|
类型
|
描述
|
| --- | --- | --- |
| $(".class") | jQuery 选择器 | 它匹配指定的CSS类中的所有元素 |
| $("html_tag") | jQuery 选择器 | 这将选择具有指定 HTML 标记的所有元素 |
| $(this) | jQuery 对象 | 它引用当前 jQuery 对象 |
| .click() | jQuery 事件绑定 | 这将处理程序绑定到元素的单击事件 |
| event.preventDefault() | jQuery 方法 | 这将防止触发事件的默认动作 |
| .focus() | jQuery 事件绑定 | 这将触发元素的焦点事件或将事件处理程序绑定到焦点事件 |
| .prop(propertyName)或.prop(propertyName, value) | jQuery 方法 | 这将为第一个匹配的元素返回指定属性的值,或者为所有匹配的元素设置指定属性的值 |
| .siblings() | jQuery 方法 | 这将检索匹配元素的兄弟元素 |
| .text() | jQuery 方法 | 这将返回每个匹配元素的组合文本内容,或者设置每个匹配元素的文本内容 |
准备
按照以下步骤构建访问同级控件的页面:
-
To demonstrate how to access sibling controls, create the following content management interface to edit reports. All text sections are read-only and are provided with EDIT links for any updates required, as shown in the following screenshot:
![Getting ready]()
-
When you click on any EDIT link, the corresponding sibling text field is made editable as follows:
![Getting ready]()
-
通过单击SAVE链接,文本字段再次变为只读。
-
要创建这个表单,启动一个新的ASP.NET Web 应用项目在 Visual Studio 中使用空模板,并将其命名为
Recipe3(或其他合适的名称)。 -
向项目中添加一个
Scripts文件夹,并将 jQuery 库包含在此文件夹中。 -
添加一个新的 web 表单,并在表单中包含 jQuery 库。
-
对于表单中的每个文本字段,我们将在
MultiLine模式下使用TextBox控件。 因此,将以下标记添加到.aspx页面。 控件的内容可以是任意的文本,如下所示: -
为了区分只读模式和更新模式,在只读模式下,我们可以通过添加以下样式给
TextBox控件一个背景色:.readtext{ background-color:powderblue; } -
另外,在EDIT/SAVE链接和 section header 中添加以下样式:
.edit { font-variant: small - caps; text-decoration: none; } .sectionHeader { font-size: 20 px; font-variant: small-caps; font-weight: 700; padding: 10 px; }
怎么做……
将下面的 jQuery 代码添加到窗体的<script>块中:
<script type="text/javascript">
$(document).ready(function() {
$("textarea").prop("readonly", true).addClass("readtext");
$(".edit").click(function(evt) {
evt.preventDefault();
var lnkText = $(this).text();
if (lnkText == "Edit") {
$(this).siblings("textarea").prop("readonly", false).removeClass("readtext").focus();
$(this).text("Save");
} else if (lnkText == "Save") {
$(this).siblings("textarea").prop("readonly", true).addClass("readtext");
$(this).text("Edit");
}
});
});
</script>
How it works…
让我们看看如何访问同级控件:
-
Initially, when the page loads in the browser, all
TextBoxcontrols are made uneditable by setting theirreadonlyproperty totrue. At runtime, theTextBoxcontrols in theMultiLinemode are rendered astextareaelements. Hence, we can use the.prop()method as follows:$("textarea").prop("readonly", true).addClass("readtext");注意事项
前面添加的
CSS类确保将背景色应用于TextBox控件。 -
所有的EDIT
LinkButton控件都绑定到一个editCSS 类上。 因此,我们可以使用 CSS 选择器为每个链接的click事件附加处理程序,如下所示:$(".edit").click(function (evt) {..}); -
When you click on any of the preceding links, firstly, prevent page submission:
evt.preventDefault();其次,获取链接的
text。 这个text可以是EDIT或者SAVE,这取决于用户的操作:var lnkText = $(this).text(); -
If the link text is EDIT, we use the
.siblings()method to traverse through other elements on the same level until we come across atextareaelement. Once the element is located, the following needs to be done:- 将
textarea元素的readonly属性设置为false,即使该字段可编辑 - 通过删除相应的样式来删除背景色
- 将光标聚焦在字段上
这可以通过在一条语句中链接这些方法来实现:
$(this).siblings("textarea").prop("readonly", false).removeClass("readtext").focus();最后,更新链接
SAVE的text:$(this).text("Save"); - 将
-
If you click on the SAVE link, the following needs to be done:
- 将兄弟元素
textarea的readonly属性设置为true,即使该字段不可编辑 - 为
textarea元素添加背景色
这可以通过以下语句中的方法链接来实现:
$(this).siblings("textarea").prop("readonly", true).addClass("readtext");接下来,更新链接
text以显示EDIT:$(this).text("Edit");注意事项
注意,通过单击SAVE链接,您可能还需要执行一些服务器端操作,例如使用 AJAX 将内容保存到数据库或文件中。
- 将兄弟元素
还有更多的…
让我们使用浏览器窗口中的开发人员工具来查看活动textarea字段属性的变化。 开发工具可以如下启动:
- 在 Internet Explorer 中,从主菜单进入Tools|F12 Developer Tools
- 从主菜单,在 Firefox 开发人员去|切换调试器工具|(Ctrl +【显示】+转变我)****
***** 在谷歌 Chrome,从主菜单,去更多的工具|开发工具(Ctrl+【T7 转变】+【显示】我)****
****将所需的断点添加到 jQuery 脚本中,如下截图所示:

逐步遍历代码,查看活动元素的readonly属性和背景颜色的变化。
参见 also
访问父控件和子控件配方
使用过滤器细化选择
jQuery 提供了一个有用的.filter()方法来使用selector或custom函数过滤元素。 在此配方中,我们将使用此方法在客户端筛选GridView控件的行。 本例中使用的结构总结如下表:
构造
|
类型
|
描述
|
| --- | --- | --- |
| $(#identifier) | jQuery 选择器 | 这将基于其ID选择一个元素。 |
| $(".class") | jQuery 选择器 | 它匹配指定 CSS 类的所有元素 |
| $("html_tag") | jQuery 选择器 | 这将选择具有指定 HTML 标记的所有元素 |
| $(this) | jQuery 对象 | 它引用当前 jQuery 对象 |
| .click() | jQuery 事件绑定 | 这将处理程序绑定到元素的click事件 |
| :eq(i) | jQuery 选择器 | 这将选择索引为i的所有元素。 |
| event. preventDefault() | jQuery 方法 | 这将防止触发事件的默认动作 |
| .filter() | jQuery 方法 | 返回匹配选择器或自定义函数的元素 |
| .find() | jQuery 方法 | 这将查找与筛选器匹配的所有元素 |
| :first-child | jQuery 选择器 | 这将选择父元素的第一个子元素 |
| .hide() | jQuery 方法 | 这将隐藏匹配的元素 |
| :not(selector) | jQuery 选择器 | 这将选择与指定选择器不匹配的元素 |
| .show() | jQuery 方法 | 这会显示匹配的元素 |
| .substring(startIndex, [endIndex]) | JavaScript 函数 | 它返回给定字符串的子字符串,从startIndex到endIndex或到字符串的末尾 |
| .text() | jQuery 方法 | 这将返回每个匹配元素的组合文本内容,或者设置每个匹配元素的文本内容 |
| :visible | jQuery 选择器 | 这将选择可见的元素,即宽度或高度为> 0 的元素 |
准备
让我们构建一个页面来使用过滤器来细化选择:
-
Let's create a web page with a
GridViewcontrol that reads data from the Products table in the Northwind database. When you run the page, all records are retrieved and displayed, as shown here:![Getting ready]()
-
When you click on any letter from A to Z above the
GridViewcontrol, the rows are filtered to show the product names that begin with the selected letter. For example, when you click on the letterR, the page will display all product names beginning with the letterR, as shown in the following screenshot:![Getting ready]()
如果没有以开头的产品名称,选择的字母没有,则会向用户显示提示信息,如下图所示:
![Getting ready]()
-
首先,创建一个新的ASP.NET Web 应用项目在 Visual Studio 中使用空模板,并将其命名为
Recipe4(或任何其他合适的名称)。 -
添加一个
Scripts文件夹到项目中,包含 jQuery 库文件在此文件夹中。 -
创建一个新的 web 表单,并添加 jQuery 库到表单中。
-
转到工具箱|Data,将GridView控件拖放到窗体上。
-
In the Design mode, mouse over the GridView control until a small arrow icon appears in the top-right corner of the screen. Click on the arrow to show the GridView Tasks menu, as shown here:
![Getting ready]()
-
Select the <New data source…> option from the Choose Data Source field from the preceding menu. This will launch the Data Source Configuration Wizard, Select SQL Database from the available options, and click on OK to proceed:
![Getting ready]()
-
On the next screen, add a connection to the Northwind database. This will launch the Configure the Select Statement screen, as shown in the following screenshot. Select the Products table, and choose few columns for display such as ProductID, ProductName, UnitPrice, and UnitsInStock. Click on Next to proceed. Test the query to complete the wizard.
![Getting ready]()
-
To display a list of letters from A to Z for filtering the
GridViewcontrol, we will use aRepeatercontrol. Hence, drag and drop a Repeater control by navigating to Toolbox | Data. In the code-behind file, populate theRepeatercontrol usingDataTableas follows:
对于 VB,代码如下:
```
Private Sub Repeater1_BindData()
Dim dt As DataTable = New DataTable()
dt.Columns.Add("Alphabet")
Dim cnt As Integer
For cnt = 65 To 90 Step 1
dt.Rows.Add(Chr(cnt))
Next
dt.AcceptChanges()
Repeater1.DataSource = dt
Repeater1.DataBind()
End Sub
```
对于 c#,代码如下:
```
private void Repeater1_BindData()
{
DataTable dt = new DataTable();
dt.Columns.Add("Alphabet");
for (int cnt= 65; cnt <= 90; ++cnt)
dt.Rows.Add((char)cnt);
dt.AcceptChanges();
Repeater1.DataSource = dt;
Repeater1.DataBind();
}
```
在前面的过程中,我们使用 ASCII 码来生成字母列表。 由于`A`的 ASCII 码为`65`,`Z`的 ASCII 码为`90`,循环从`65`运行到`90`,从 ASCII 码生成所需的字符。 生成的字符存储在`DataTable`中的`Alphabet`列中。 此列将在 Repeater 标记中用于显示。
- To populate the
Repeatercontrol, call the preceding procedure on loading the page:
对于 VB,代码如下:
```
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Repeater1_BindData
End Sub
```
对于 c#,代码如下:
```
protected void Page_Load(object sender, EventArgs e)
{
Repeater1_BindData();
}
```
- 在设计模式下,在
Repeater控件的<ItemTemplate>元素中,添加一个LinkButton控件以链接按钮的形式显示每个字母。 - 另外,向窗体添加一个
Label控件。 当没有为特定筛选器检索记录时,将显示此Label。 .aspx页面的最终标记如下:
```
<table>
<tr>
<td>
<asp:Repeater ID="Repeater1" runat="server" >
<ItemTemplate>
<asp:LinkButton CssClass="filterLink" runat="server"><%#Eval("Alphabet") %></asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
</td>
</tr>
</table>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ProductID" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="ProductID" HeaderText="Product ID" InsertVisible="False" ReadOnly="True" SortExpression="ProductID" />
<asp:BoundField DataField="ProductName" HeaderText="Product Name" SortExpression="ProductName" />
<asp:BoundField DataField="UnitPrice" HeaderText="Unit Price" SortExpression="UnitPrice" />
<asp:BoundField DataField="UnitsInStock" HeaderText="Units In Stock" SortExpression="UnitsInStock" />
</Columns>
</asp:GridView>
<br />
<asp:Label ID="lblMessage" runat="server" Text="No records found" CssClass="message"></asp:Label>
```
- Add the following style to display information messages to the user:
```
.message{
color:red;
}
```
下面的样式将给各自的元素填充:
```
.filterLink{
padding:2px;
}
th,td{
padding:5px;
}
```
怎么做……
将以下 jQuery 代码添加到窗体的<script>块中:
<script type="text/javascript">
$(document).ready(function () {
$("#<%=lblMessage.ClientID%>").hide();
$(".filterLink").click(function (evt) {
evt.preventDefault();
var filterLetter = $(this).text();
$("#<%=GridView1.ClientID%> tr:not(:first-child)").hide().filter(function () {
if ($(this).find("td:eq(1)").text().substring(0, 1) == filterLetter)
return this;
}).show();
if (($("#<%=GridView1.ClientID%> tr:visible").length - 1) == 0)
$("#<%=lblMessage.ClientID%>").show();
else
$("#<%=lblMessage.ClientID%>").hide();
});
});
</script>
How it works…
下面的步骤显示了使用过滤器细化选择:
-
当页面在浏览器中启动时,最初,用于向用户显示信息消息的
Label控件是隐藏的:$("#<%=lblMessage.ClientID%>").hide(); -
GridView控件上面的A到Z的每个字母被分配一个filterLinkCSS 类。 使用 CSS 选择器将事件处理程序附加到这些链接的click事件,如下所示: -
If you click on any of the preceding links, the page will be prevented from posting back, as follows:
evt.preventDefault();接下来,检索被单击的字母。 这可以通过检索
text link来实现:var filterLetter = $(this).text();若要只返回产品名称以所单击字母开头的行,请使用
tr:not(:first-child)选择器选择除标题行以外的所有行。 这些行最初是隐藏的:$("#<%=GridView1.ClientID%> tr:not(:first-child)").hide()接下来,应用
filter()方法。 读取td:eq(1)产品名称单元格,并比较其字符是否以单击的字母开头:.filter(function () { if ($(this).find("td:eq(1)").text().substring(0, 1) == filterLetter) return this; })只有满足
.filter()方法的行才会返回并显示:.show(); -
接下来,如果从筛选中没有检索到行,则显示信息消息,我们使用
:visible筛选器检查可见的行数。 如果只有标题行可见,我们可以显示消息来通知用户没有返回行:if (($("#<%=GridView1.ClientID%> tr:visible").length - 1) == 0) $("#<%=lblMessage.ClientID%>").show(); Otherwise, the message is hidden: else $("#<%=lblMessage.ClientID%>").hide();
还有更多的…
.children()方法是.find()方法的替代方法。 这两个方法之间的区别在于.children()方法只沿着 DOM 树向下移动了一层。 由于td元素是tr元素的直接后代,让我们看看<script>块中的以下语句:
if ($(this).find("td:eq(1)").text().substring(0, 1) == filterLetter)
可以使用children()方法修改如下:
if ($(this).children("td:eq(1)").text().substring(0, 1) == filterLetter)
参见 also
添加/删除 DOM 元素配方
在运行时向控件添加项
在本教程中,我们将使用 jQuery 向不同的 ASP 中添加项目.NET 控件,如DropDownList、ListBox和BulletedList在运行时。 本例中使用的结构总结如下:
构造
|
类型
|
描述
|
| --- | --- | --- |
| $("#identifier") | jQuery 选择器 | 它使用其ID来选择一个元素。 |
| $.map() | jQuery 函数 | 这将数组或对象转换为另一个数组 |
| .append() | jQuery 方法 | 这将在每个匹配元素的末尾插入内容 |
| .click() | jQuery 事件绑定 | 这将处理程序绑定到元素的click事件 |
| event.preventDefault() | JavaScript 函数 | 这将防止触发事件的默认动作 |
| .focus() | jQuery 事件绑定 | 这将触发元素的焦点事件或将事件处理程序绑定到焦点事件 |
| .prepend() | jQuery 方法 | 这将在每个匹配元素的开头插入内容 |
| .split() | JavaScript 函数 | 这将使用指定的字符作为分隔符将字符串拆分为子字符串 |
| .trim() | JavaScript 函数 | 这将从字符串的开头和结尾删除一个空格 |
| .val() | jQuery 方法 | 返回第一个匹配元素的值,或者设置每个匹配元素的值 |
准备
让我们构建一个页面,在运行时向控件添加项:
-
In this recipe, let's create a web page with different types of controls to which items will be added at runtime. We will also provide a textbox field where the user can enter the items that need to be added.
![Getting ready]()
让我们假设用户需要向控件添加多个项。 这可以通过输入用逗号分隔的项目来完成,如下面的截图所示:
![Getting ready]()
-
When you click on the Add Items button, the new items are reflected in the controls, as shown in the following screenshot:
![Getting ready]()
-
让我们通过创建一个新的ASP 来开始.NET Web 应用项目在 Visual Studio 中使用空的模板,并将其命名为
Recipe5(或其他合适的名称)。 -
在项目中创建一个
Scripts文件夹,并将 jQuery 库添加到该文件夹中。 -
创建一个新的 web 表单,并在表单中包含 jQuery 库。
-
在窗体上拖放所需的控件,以在页面上创建以下标记:
<div> <asp:Label ID="lblDescription" runat="server" Text="Key in the items to add in the text field below. To add more than one item, separate by comma."></asp:Label> <br /><br /> <asp:TextBox ID="txtAddItem" runat="server"></asp:TextBox> <asp:Button ID="btnAdd" runat="server" Text="Add Items" /> <br /> <p class="sectionHeader">ListBox control</p> <asp:ListBox ID="lstBox" runat="server" Width="200px"> <asp:ListItem Text="First Item" Value="First Item"></asp:ListItem> </asp:ListBox> <br /> <p class="sectionHeader">DropDownList control</p> <asp:DropDownList ID="ddlList" runat="server" Width="200px"> <asp:ListItem Text="First Item" Value="First Item"></asp:ListItem> </asp:DropDownList> <br /> <p class="sectionHeader">BulletedList control</p> <asp:BulletedList ID="lstList" runat="server"> <asp:ListItem Text="First Item" Value="First Item"></asp:ListItem> </asp:BulletedList> </div> -
添加一些样式到节标题:
.sectionHeader{ font-size:20px; font-variant:small-caps; font-weight:700; }
怎么做……
将以下 jQuery 代码添加到窗体的<script>块中:
<script type="text/javascript">
$(document).ready(function() {
$("#<%=txtAddItem.ClientID%>").focus();
$("#<%=btnAdd.ClientID%>").click(function(evt) {
evt.preventDefault();
var addItemText = $("#<%=txtAddItem.ClientID%>").val().trim();
if (addItemText != "") {
var arrString = addItemText.split(",");
$("#<%=lstBox.ClientID%>").prepend(
$.map(arrString, function(v) {
return $("<option value=" + v.trim() + ">" + v.trim() + "</option>");
}));
$("#<%=ddlList.ClientID%>").append(
$.map(arrString, function(v) {
return $("<option>").val(v.trim()).text(v.trim());
}));
$("#<%=lstList.ClientID%>").append(
$.map(arrString, function(v) {
return $("<li>" + v.trim() + "</li>");
}));
}
$("#<%=txtAddItem.ClientID%>").val("").focus();
});
});
</script>
How it works…
下面的是在运行时向控件添加项的步骤:
-
在浏览器中加载页面时,通过使用
.focus()函数将光标聚焦在文本字段中:$("#<%=txtAddItem.ClientID%>").focus(); -
事件处理程序被附加到Add Items按钮的
click事件:$("#<%=btnAdd.ClientID%>").click(function (evt) {…}); -
如果单击前面的按钮,第一个任务是防止将页面发布到服务器:
evt.preventDefault(); -
接下来,检索文本字段的内容和
trim以删除空白:var addItemText = $("#<%=txtAddItem.ClientID%>").val().trim(); -
Check whether the content of the preceding field is empty:
if (addItemText != "")如果它不为空,通过使用逗号作为分隔符来分割字符串,从输入的文本构建一个数组:
var arrString = addItemText.split(",");注意事项
如果字符串中没有逗号,则数组将由单个元素组成。
-
现在,使用
.map()函数将该数组转换为包含<option>元素的列表,以便<option>元素的文本和值都等于该下标处的数组元素。 -
将
option元素列表前置到ListBox控件,即新元素将作为ListBox控件中的起始元素出现:$("#<%=lstBox.ClientID%>").prepend($.map(arrString, function (v) { return $("<option value=" + v.trim() + ">" + v.trim() + "</option>"); })); -
同样的
option元素列表也可以添加到DropDownList控件中。 当使用.append()函数时,新项目将出现在列表的末尾:$("#<%=ddlList.ClientID%>").append($.map(arrString, function (v) { return $("<option>").val(v.trim()).text(v.trim()); })); -
为了向
BulletedList控件添加项目,我们使用.map()函数来构建一个包含<li>元素的列表,因为在运行时,BulletedList控件将每个ListItem控件呈现为<li>元素。 所以,增加的项目如下:$("#<%=lstList.ClientID%>").append($.map(arrString, function(v){ return $("<li>" + v.trim() + "</li>"); })); -
最后,在向前面的控件添加元素之后,清除文本字段并将光标聚焦于该字段,以便准备接受下一组输入:
```
$("#<%=txtAddItem.ClientID%>").val("").focus();
```
参见 also
添加/删除 DOM 元素配方****
五、 ASP.NET 中的视觉效果
本章探讨了可以应用于 ASP 的各种视觉效果和动画.NET 控件使用 jQuery。 本章将介绍以下食谱:
- 动画菜单控件
- 动画标签控件来创建一个数字时钟
- 动画 AdRotator 控件的 alt 文本
- 在 TreeView 控件中动画图像
- 在 Panel 控件中创建滚动文本
- 使用 Panel 控件创建垂直手风琴菜单
- 显示/隐藏带有爆炸效果的 GridView 控件
简介
jQuery 简化了在网页上添加吸引人的视觉效果。 该库提供了许多支持方法,用于显示、隐藏、淡出、滑动、切换和其他自定义动画。 让我们简单地看一下这些方法:
-
Showing and hiding elements:
|jQuery method
|
description
|
| --- | --- |
|.show()| This will display matched elements |
|.hide()| This will hide matching elements |
|.toggle()| Show or hide matched elements | -
Fading elements:
|jQuery method
|
description
|
| --- | --- |
|.fadeIn()| This animates matched elements by gradually increasing their opacity until their value is 1, that is, They become opaque. |
|.fadeOut()| This gives animation effect by gradually reducing the opacity of matching elements. Until they reach the value of zero, that is, they become transparent. |
|.fadeTo()| This will animate the opacity of the matching element to the specified value. |
|.fadeToggle()| This activates the opacity of matched elements to hide or show them. | -
Sliding elements:
|jQuery method
|
Description
|
| --- | --- |
|.slideUp()| This hides elements by sliding up. |
|.slideDown()| This will display the element with the download slide motion. |
|.slideToggle()| This will hide or display matched elements by sliding motion. | -
Custom effects:
jQuery method
|Description
|
| --- |
|.animate()| This performs custom animations on the specified CSS properties. Most of the properties that can be animated are numeric CSS properties, such as font size, width, height, opacity, top, left, right, and so on. |
前面所有的支持方法都允许您以毫秒为单位指定动画的持续时间。 所有动画的默认持续时间为 400 毫秒。jQuery 还提供了关键字,例如慢(600 毫秒)和快(200 毫秒)来指定持续时间。 与较小的值相比,持续时间较大的值表示较慢的动画。
-
Stopping animations:
|jQuery method
|
Description
|
| --- | --- |
|.stop()| This will stop all animations that are running. |
|.finish()| This will stop the running animation, delete the queued animation, And complete the animation on the matching element |
动画菜单控件
ASP.NETMenu控件可以在网站上快速创建菜单。 这个食谱演示了如何添加文本动画,例如闪烁效果和改变mouseover菜单项的字体颜色。 本例中使用的结构总结如下表:
构造
|
类型
|
描述
|
| --- | --- | --- |
| $(".class") | jQuery 选择器 | 它匹配指定 CSS 类的所有元素。 |
| $("html_tag") | jQuery 选择器 | 这将选择具有指定 HTML 标记的所有元素。 |
| $(this) | jQuery 对象 | 它引用当前 jQuery 对象。 |
| .css() | jQuery 方法 | 这将获取第一个匹配元素的 style 属性,或者设置每个匹配元素的 style 属性。 |
| .fadeIn() | jQuery 方法 | 这将通过逐渐增加匹配元素的不透明度来赋予其动画效果,直到它的值为 1,也就是说,它变得不透明。 |
| .fadeOut() | jQuery 方法 | 这通过逐渐减少匹配元素的不透明度来赋予其动画效果,直到它的值为 0,也就是说,它变得透明。 |
| mouseout | jQuery 的事件 | 当鼠标指针离开控件时触发此操作。 它对应于 JavaScript 的mouseout事件。 |
| mouseover | jQuery 的事件 | 当鼠标指针进入控件时触发。 它对应于 JavaScript 的mouseover事件。 |
| .on() | jQuery 事件绑定 | 这将一个或多个事件的事件处理程序附加到匹配的元素。 |
准备
按照以下步骤创建一个将应用动画效果的菜单:
-
Let's create a web page with a horizontal menu, as shown in the following screenshot. By moving the mouse pointer on any main menu item, the font color changes and the text blinks once.
![Getting ready]()
同样,通过将鼠标指针移动到任意子菜单项上,字体颜色改变,文本闪烁:
![Getting ready]()
将鼠标指针移出主菜单或子菜单项,即可恢复原来的字体颜色。
-
要建立这个网页,创建一个新的ASP.NET Web 应用项目在 Visual Studio 中使用空模板,并将其命名为
Recipe1(或任何其他合适的名称)。 -
将 jQuery 库添加到
Scripts文件夹。 -
创建一个新的 web 表单,并在表单中包含 jQuery 库。
-
进入工具箱|导航,在窗体上拖放一个
Menu控件。 -
In the Properties window of the
Menucontrol, set the Layout | Orientation property to Horizontal, as shown here:![Getting ready]()
-
In the Design mode, move the mouse pointer on the
Menucontrol until a small arrow icon appears on the top-right corner of the control. Click on the arrow to open the Menu Tasks window, as shown here:![Getting ready]()
-
Click on the Edit Menu Items link in the preceding Menu Tasks window to open the Menu Item Editor window. Create the root and child menu items, as shown in the following screenshot. You will need to update the ImageUrl, Text, and Value properties of the main menu (root) items, for example, Home, User Accounts, Reports, and Settings. For the submenu items, you will need to update just the Text and Value properties:
![Getting ready]()
-
在Solution Explorer选项卡中右键单击项目,并导航到Add|New folder,将一个
images文件夹添加到项目中。 包括主菜单项的图标。 -
表单的最终标记如下:
```
<div id="container">
<asp:Menu ID="Menu1" runat="server" Orientation="Horizontal">
<Items>
<asp:MenuItem Text="Home" Value="Home" ImageUrl="~/images/home.png"></asp:MenuItem>
<asp:MenuItem Text="User Accounts" Value="User Accounts" ImageUrl="~/images/accounts.png">
<asp:MenuItem Text="Create Account" Value="Create Account"></asp:MenuItem>
<asp:MenuItem Text="Edit / View Accounts" Value="Edit / View Accounts"></asp:MenuItem>
<asp:MenuItem Text="Monitor Account" Value="Monitor Account"></asp:MenuItem>
</asp:MenuItem>
<asp:MenuItem Text="Reports" Value="Reports" ImageUrl="~/images/reports.png">
<asp:MenuItem Text="Account Usage" Value="Account Usage"></asp:MenuItem>
<asp:MenuItem Text="Activity Log" Value="Activity Log"></asp:MenuItem>
<asp:MenuItem Text="Account Specific" Value="Account Specific"></asp:MenuItem>
</asp:MenuItem>
<asp:MenuItem Text="Settings" Value="Settings" ImageUrl="~/images/settings.png">
<asp:MenuItem Text="Update Profile" Value="Update Profile"></asp:MenuItem>
<asp:MenuItem Text="Change Password" Value="Change Password"></asp:MenuItem>
</asp:MenuItem>
</Items>
<StaticMenuItemStyle HorizontalPadding="35px" />
</asp:Menu>
</div>
```
- Note that in the preceding markup, the
Menucontrol is included in adivcontainer. Apply the following style to thisdivcontainer:
```
#container {
background-color:lightgray;
width:100%;
}
```
这将为整个`Menu`控件提供背景色,并保持其宽度为页面宽度的 100%。
- 在运行时,
Menu控件为主菜单项呈现level1CSS 类,为子菜单项呈现level2CSS 类。 因此,对这些项目应用以下样式:
```
#Menu1 .level1{
padding:5px;
font-variant:small-caps;
color:black;
font-size:20px;
font-weight:700;
font-family:'Times New Roman', Times, serif;
}
#Menu1 .level2{
background-color:aquamarine;
color:green;
padding:5px;
}
```
- 要在主菜单项中的图像和文本之间创建间距,请向页面添加以下样式:
```
#Menu1 img{
padding-right:5px;
}
```
怎么做……
将下面的 jQuery 代码添加到页面的script块中:
<script type="text/javascript">
$(document).ready(function() {
$(".level1 a, .level2 a").on("mouseover", function() {
$(this).css("color", "red");
$(this).fadeOut("fast").fadeIn("fast");
});
$(".level1 a").on("mouseout", function() {
$(this).css("color", "black");
});
$(".level2 a").on("mouseout", function() {
$(this).css("color", "green");
});
});
</script>
How it works…
菜单动画的工作方式如下:
-
用Ctrl+S保存页面,然后用F5运行。 这将在网页上启动菜单。
-
When you move the mouse over any main menu or submenu item, the following corresponding event handler will be executed:
$(".level1 a, .level2 a").on("mouseover", function () {…});前面的选择器将
mouseover事件的事件处理程序附加到level1和level2超链接上。 -
In the preceding event handler, firstly, the font color is changed to red by updating the
cssproperty as follows:$(this).css("color", "red");其次,通过完全淡出来添加一个闪烁的效果,使其隐藏,然后,通过淡入来逐渐使控件可见,如下所示:
$(this).fadeOut("fast").fadeIn("fast");因此,淡出和淡入效果被串联起来给文本一个闪烁的效果。
fadeOut()和fadeIn()方法的调用持续时间为fast,为 200 ms。 -
当鼠标指针移出主菜单或子菜单项时,将执行相应的
mouseout事件处理程序。 该事件处理程序将恢复字体颜色为原始值,如下所示:
参见 also
使用面板控件创建垂直手风琴菜单
动画 Label 控件来创建数字时钟
这个配方使用自定义动画效果来创建一个闪烁的数字时钟,以 hh:mm:ss 格式显示当前时间。 本例中使用的结构总结如下表:
|构造
|
类型
|
描述
|
| --- | --- | --- |
| $("#identifier") | jQuery 选择器 | 这将使用其 ID 选择一个元素。 |
| .animate() | jQuery 方法 | 这将对指定的 CSS 属性执行自定义动画。 |
| Date | JavaScript 对象 | 这是一个存储日期/时间信息的对象:年、月、日、小时、分钟和秒。 |
| Date.getHours() | JavaScript 函数 | 它返回从 0 到 23 的小时数。 |
| Date.getMinutes() | JavaScript 函数 | 它返回从 0 到 59 的分钟数。 |
| Date.getSeconds() | JavaScript 函数 | 它返回从 0 到 59 的秒数。 |
| opacity | CSS 属性 | 这是元素的透明度程度。 |
| setInterval(function, delay) | JavaScript 函数 | 此在指定的延迟之后重复执行一个函数(以毫秒为单位)。 |
| .slice() | JavaScript 函数 | 它提取字符串的一部分。 作为参数传递给函数的负数从字符串末尾提取所需的字符数。 |
| .text() | jQuery 方法 | 这将返回每个匹配元素的组合文本内容,或者设置每个匹配元素的文本内容。 |
准备
使用 jQuery 制作一个数字时钟。
-
Let's build the digital clock by animating a
Labelcontrol. The control will display the current time in the hh:mm:ss format at any point of time. Once every second, theLabelcontrol will be cleared and the new time will be displayed, giving the clock a blink effect.![Getting ready]()
-
首先,添加一个新的ASP.NET Web 应用项目在 Visual Studio 中使用空模板,并将其命名为
Recipe2(或任何其他合适的名称)。 -
在项目中添加一个
Scripts文件夹,并将 jQuery 库文件添加到该文件夹中。 -
向项目中添加一个新的 web 表单。 在 Web 表单中包含 jQuery 库。
-
在
Panel控件中添加Label控件,如下所示: -
将下面的 CSS 样式添加到包含的
Panel控件中:
怎么做……
在页面的script块中包含以下 jQuery 代码:
<script type="text/javascript">
$(document).ready(function() {
setInterval(animateLabel, 1000);
function animateLabel() {
var time = getCurrentTime();
$("#<%=lblTime.ClientID%>").text(time);
$("#<%=lblTime.ClientID%>").animate({
opacity: 0
}, 950).animate({
opacity: 1
}, 50);
}
function getCurrentTime() {
var dt = new Date();
var dtHour = dt.getHours(); // returns a number from 0 to 23
var dtMinutes = ("0" + dt.getMinutes()).slice(-2);
var dtSeconds = ("0" + dt.getSeconds()).slice(-2);
var strAmPm = "";
if (dtHour >= 12)
strAmPm = "PM";
else
strAmPm = "AM";
if (dtHour > 12)
dtHour -= 12;
var time = dtHour + ":" + dtMinutes + ":" + dtSeconds + " " + strAmPm;
return time;
}
});
</script>
How it works…
数字时钟的工作原理如下:
-
保存并运行该页面。 文档就绪后,
setIntervalJavaScript 函数每1000毫秒调用animateLabel方法,即每秒钟调用一次:setInterval(animateLabel, 1000); -
animateLabel方法使用getCurrentTime方法获取当前时间,稍后我们将看到:var time = getCurrentTime(); -
接下来,将
Label控件的文本设置为上一步中检索到的时间:$("#<%=lblTime.ClientID%>").text(time); -
The opacity of the
Labelcontrol is animated to reach0in950ms so thatLabelis completely invisible at the end of the animation. The next animation is chained at the end of this animation, and the opacity of theLabelcontrol is increased to1in50ms so that theLabelcontrol is completely opaque after a blink effect:$("#<%=lblTime.ClientID%>").animate({ opacity: 0 }, 950).animate({ opacity: 1 }, 50);因此,1000ms 的间隔被分为两部分,950 ms 和 50ms。
注意事项
元素的不透明度是指该元素的透明程度。 不透明度可以取 0 到 1 的任意值。
当不透明度为 1 时,该元素是不透明的。
当不透明度为 0 时,元素是透明的,也就是不可见的。
当透明度为> 0 和< 1 时,它是半透明的,也就是说,它的背景是可见的。
-
Next, let's take a look at the
getCurrentTimemethod that returns the current time in the hh:mm:ss format. This method first creates aDateobject:var dt = new Date();接下来,从 date 对象获取小时值,从 0 到 23 的整数值:
var dtHour = dt.getHours();从 date 对象获取时间。 分钟可以是单个数字,所以在前面填充一个零,然后使用
slice提取最后两个字符,如下所示:var dtMinutes = ("0" + dt.getMinutes()).slice(-2);从 date 对象获取秒数。 秒也可以是单个数字,所以在前面填充一个 0,然后使用
slice提取最后两个字符,如下所示:var dtSeconds = ("0" + dt.getSeconds()).slice(-2); -
Let a
strAmPmvariable store AM or PM as required. Initialize this variable to an empty string:var strAmPm = "";如果小时数大于或等于
12,则设置strAMPM为PM,否则设置为AM:if (dtHour >= 12) strAmPm = "PM"; else strAmPm = "AM"; -
Also, display the hours from 0 to 12 instead of 0 to 23 as follows:
if (dtHour > 12) dtHour -= 12;现在,使用前面计算的值构建格式化为小时:分钟:秒的字符串。 返回
time字符串var time = dtHour + ":" + dtMinutes + ":" + dtSeconds + " " + strAmPm; return time;
参见 also
在 Panel 控件中创建滚动文本配方
动画 AdRotator 控件的 alt 文本
控件用于在网页上显示广告横幅。 每当页面被刷新时,控件加载一个新的横幅。 在本演示中,让我们增强AdRotator控件,以使用滑动动画显示广告横幅的 alt 文本。 本例中使用的构造如下:
构造
|
类型
|
描述
|
| --- | --- | --- |
| $("#identifier") | jQuery 选择器 | 这将使用其 ID 选择一个元素 |
| $("html_tag") | jQuery 选择器 | 这将选择具有指定 HTML 标记的所有元素 |
| .addClass() | jQuery 方法 | 这会将指定的 CSS 类添加到每个匹配的元素中 |
| .animate() | jQuery 方法 | 这将对指定的 CSS 属性执行自定义动画 |
| .css() | jQuery 方法 | 这将获取第一个匹配元素的 CSS 属性,或者为每个匹配元素设置一个或多个 CSS 属性 |
| event.pageX | jQuery 事件属性 | 这将返回相对于文档左边缘的鼠标位置 |
| event.pageY | jQuery 事件属性 | 这将返回相对于文档顶部边缘的鼠标位置 |
| .hide() | jQuery 方法 | 这将隐藏匹配的元素 |
| .hover() | jQuery 事件绑定 | 这绑定了mouseover和mouseout事件的事件处理程序 |
| left | CSS 属性 | 这个是元素左边缘的位置 |
| opacity | CSS 属性 | 这是元素的透明度程度 |
| .prop(propertyName)或.prop(propertyName, value) | jQuery 方法 | 这将为第一个匹配的元素返回指定属性的值,或者为所有匹配的元素设置指定属性的值 |
| .slideDown() | jQuery 方法 | 这将显示带有下载幻灯片运动的元素 |
| .text() | jQuery 方法 | 这将返回每个匹配元素的组合文本内容,或者设置每个匹配元素的文本内容 |
| top | CSS 属性 | 这是元素的上边缘的位置 |
准备
遵循这些步骤构建一个网页与 AdRotator:
-
We will create a web page with an
AdRotatorcontrol that displays ad banners from an advertisement XML file. The alt text for each banner is also saved in the XML file. At runtime, when the mouse pointer is moved on the banner, its opacity reduces, and the alt text is displayed in a sliding panel, as shown in the following screenshot:![Getting ready]()
当页面被刷新时,控件从 XML 文件中加载另一个广告横幅。 同样的效果可以在更新的横幅上看到,如下所示:
![Getting ready]()
-
首先,创建一个新的ASP.NET Web 应用在 Visual Studio 中使用空模板,并将其命名为
Recipe3(或其他合适的名称)。 -
将 jQuery 库文件包含在项目的
Scripts文件夹中。 -
添加一个新的 web 表单到项目中,并在表单中包含 jQuery 库。
-
转到工具箱|Standard,然后在窗体上拖放一个
AdRotator控件。 另外,在AdRotator控件下面的窗体中添加一个Panel控件。 这个面板将用于在广告横幅上显示 alt 文本。 -
在解决方案资源管理器选项卡中,右键单击项目,然后转到添加|添加 ASP.NET 文件夹,选择
App_Data文件夹。 这会将App_Data文件夹添加到项目中,如果该文件夹不存在的话。 -
右键单击
App_Data文件夹,选择添加|XML 文件。 在对话框中,按AdsFile.xml键。 这个 XML 文件将用于存储将要在AdRotator控件中显示的广告数据。 -
Add the following content to the XML file. Note that the root node is
Advertisementsand the details of each ad are saved in theAdnode:<Advertisements> <Ad> <ImageUrl>~/images/packtlib-logo-dark.png</ImageUrl> <height>56</height> <width>115</width> <NavigateUrl>https://www.packtpub.com/packtlib</NavigateUrl> <AlternateText>Access books and videos from Packt Library.</AlternateText> <Impressions>80</Impressions> <Keyword>Packt</Keyword> </Ad> <Ad> <ImageUrl>~/images/learning_jquery.jpg</ImageUrl> <height>92</height> <width>115</width> <NavigateUrl>https://www.packtpub.com/web-development/learning-jquery-fourth- edition</NavigateUrl> <AlternateText>Learning jQuery, Fourth Edition.</AlternateText> <Impressions>80</Impressions> <Keyword>Packt</Keyword> </Ad> </Advertisements>
|Ad节点中的每个子节点都提供了独特的功能,概述如下:节点
|
描述
|
| --- | --- |
|ImageUrl| 这是要显示的图像的 URL。 |
|Height| 这是图像的高度,以像素为单位。 |
|Width| 这是图像的宽度,以像素为单位。 |
|NavigateUrl| 这是当您点击广告横幅时要加载的页面的 URL。 |
|AlternateText| 这是图像不可用时显示的文本。 |
|Impressions| 这是表示为数字的图像被显示的可能性。 |
|Keyword| 这是图像的类别。 此字段可用于过滤特定的广告。 | -
将
AdRotator控件的AdvertisementFile属性设置为上述文件。 因此,表单的标记如下:<asp:AdRotator ID="AdRotator1" AdvertisementFile="~/App_Data/AdsFile.xml" runat="server" /> <asp:Panel ID="pnlDescription" runat="server"></asp:Panel> -
将以下 CSS 类添加到页面的
head元素中。 当我们显示标题的 alt 文本时,此样式将应用于Panel控件:
```
<style type="text/css">
.altTextStyle {
background-color:lightblue;
border-color:blue;
border-style:solid;
border-width:1px;
position:absolute;
color:indigo;
padding:5px;
}
</style>
```
- 向项目中添加一个新的
images文件夹,并将所需的广告横幅添加到该文件夹中。
怎么做……
在页面的script块中包含以下 jQuery 代码:
<script type="text/javascript">
$(document).ready(onReady);
function onReady() {
$("#<%=pnlDescription.ClientID%>").addClass("altTextStyle").hide();
$("#<%=AdRotator1.ClientID%>").hover(
function(evt) {
var altText = $("#<%=AdRotator1.ClientID%> img").prop("alt");
$("#<%=pnlDescription.ClientID%>").text(altText).css("left", evt.pageX).css("top", evt.pageY);
$("#<%=pnlDescription.ClientID%>").slideDown("slow");
$("#<%=AdRotator1.ClientID%> img").animate({
opacity: 0.5
}, "slow");
},
function() {
$("#<%=pnlDescription.ClientID%>").hide();
$("#<%=AdRotator1.ClientID%> img").animate({
opacity: 1
}, "slow");
});
}
</script>
How it works…
AdRotator 的工作原理如下:
-
当页面在浏览器中启动时,文档就绪时调用
onReady函数:$(document).ready(onReady); -
在
onReady函数中,将altTextStyleCSS 类添加到Panel控件中,然后隐藏该控件:$("#<%=pnlDescription.ClientID%>").addClass("altTextStyle").hide(); -
The
hoverevent binder is used to attach event handlers for themouseoverandmouseoutevents as follows:$("#<%=AdRotator1.ClientID%>").hover(function(){...}, function(){...});在这里,第一个函数是
mouseover事件的处理程序,而第二个函数是mouseout事件的处理程序。 -
At runtime, the
AdRotatorcontrol is rendered as an<img>element enclosed within an<a>element, as shown in the following figure. To view the HTML source of the page, right-click on the browser window, and select View Source:![How it works…]()
因此,
mouseover的事件处理程序可以从渲染的图像中检索横幅的 alt 文本属性,如下所示:var altText = $("#<%=AdRotator1.ClientID%> img").prop("alt"); -
The text of the
Panelcontrol is set to the preceding text. The location of the mouse is retrieved using theevent.pageXandevent.pageYproperties. The left and top locations of thePanelcontrol can now be set to these coordinates so that thePanelhovers over the mouse pointer:$("#<%=pnlDescription.ClientID%>").text(altText).css("left", evt.pageX).css("top", evt.pageY);现在已经初始化了
Panel控件的文本和位置,它将使用slideDown函数以slow为持续时间进行动画:$("#<%=pnlDescription.ClientID%>").slideDown("slow");广告横幅也被动画化,以
slow的速度降低其不透明度为 50%:$("#<%=AdRotator1.ClientID%> img").animate({ opacity: 0.5 }, "slow"); -
The
mouseoutevent handler accomplishes two tasks. Firstly, the alt textPanelis hidden from the view as follows:$("#<%=pnlDescription.ClientID%>").hide();其次,通过缓慢地将不透明度增加到 1 来恢复横幅的完全可见性:
$("#<%=AdRotator1.ClientID%> img").animate({ opacity: 1 }, "slow");
还有更多的…
控件仅在刷新页面时显示新的广告条。 为了定期刷新AdRotator控件,我们可以将该控件放在UpdatePanel控件中,并使用 AJAX 来刷新它。 可以这样做:
-
通过导航到工具箱|AJAX Extensions,拖动并放下
ScriptManager控件和UpdatePanel控件。 -
为了定期刷新广告横幅,我们还需要一个
Timer控制。 因此,通过导航到工具箱|AJAX Extensions来拖放Timer控件。 -
In the Properties window, as shown in the following screenshot, set the Interval property of the timer to
5000ms. This will cause theTimercontrol to tick every 5 seconds:![There's more…]()
-
Now, open the Properties window of the
UpdatePanelcontrol, and expand the Triggers property, as shown here:![There's more…]()
在UpdatePanelTrigger 集合编辑器窗口这是启动,点击添加
AsyncPostBack【显示】按钮来添加一个触发器,并设置ControlID房地产Timer1和EventName【病人】Tick,如下面屏幕截图所示。 点击OK关闭窗口:****![There's more…]()
-
将
AdRotator和Panel控件置于UpdatePanel控件的ContentTemplate控件中。 -
After every AJAX refresh of the
UpdatePanelcontrol, the client script code is rewritten, and the jQuery code that we wrote to animate the alt text is lost. Hence, we need to rewrite our jQuery code on the page using theSystem.Application.add_loadmethod as follows:<script type="text/javascript"> Sys.Application.add_load(onReady); </script>前面的脚本也包含在
UpdatePanel控件的ContentTemplate控件中。 -
因此,表单标记将变为以下代码:
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager> <asp:Timer ID="Timer1" runat="server" Interval="5000"></asp:Timer> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <Triggers> <asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" /> </Triggers> <ContentTemplate> <script type="text/javascript"> Sys.Application.add_load(onReady); </script> <asp:AdRotator ID="AdRotator1" AdvertisementFile="~/App_Data/AdsFile.xml" runat="server" /> <asp:Panel ID="pnlDescription" runat="server"></asp:Panel> </ContentTemplate> </asp:UpdatePanel>
参见 also
树视图控件配方中的动画图像
在 TreeView 控件中动画图像
一个TreeView控件使您能够以分层格式显示数据。 让我们应用动画来放大和缩小TreeView控件的节点中的图像。 我们还将看一看使用 jQuery UI 库的简化机制。 本例中使用的构造如下:
构造
|
类型
|
描述
|
| --- | --- | --- |
| $("#identifier") | jQuery 选择器 | 这将使用其 ID 选择一个元素。 |
| $("html_tag") | jQuery 选择器 | 这将选择具有指定 HTML 标记的所有元素。 |
| $(this) | jQuery 对象 | 它引用当前 jQuery 对象。 |
| .animate() | jQuery 方法 | 这将对指定的 CSS 属性执行自定义动画。 |
| [attr$="value"] | jQuery 选择器 | 这将选择一个以value字符串结尾的指定属性的元素。 |
| .find() | jQuery 方法 | 这将查找与筛选器匹配的所有元素。 |
| height | CSS 属性 | 这是元素的高度。 |
| mouseout | jQuery 的事件 | 当鼠标指针离开控件时触发此操作。 它对应于 JavaScript 的mouseout事件。 |
| mouseover | jQuery 的事件 | 当鼠标指针进入控件时触发。 它对应于 JavaScript 的mouseover事件。 |
| .on() | jQuery 事件绑定 | 这将一个或多个事件的事件处理程序附加到匹配的元素。 |
| .stop() | jQuery 方法 | 这会停止所有正在运行的动画。 |
| width | CSS 属性 | 这是元素的宽度。 |
准备
按照的步骤在网页上设置一个 TreeView 控件:
-
Let's create a web page to display the list of employees (with their profile photos) in various departments of a company in a tree structure, as shown in the following screenshot:
![Getting ready]()
要放大某个员工的个人资料照片,只需要将鼠标指针移动到照片上,如下图所示:
![Getting ready]()
通过将鼠标指针移出照片,它会缩小到原来的缩略图大小。
-
让我们通过创建ASP 来开始.NET Web 应用项目在 Visual Studio 中使用空的模板并将其命名为
Recipe4(或其他合适的名称)。 -
向项目中添加一个
Scripts文件夹,并将 jQuery 库文件添加到此文件夹中。 -
添加一个新的 web 表单到项目中,并在表单中包含 jQuery 库。
-
通过导航到工具箱|Navigation,在窗体上拖放
TreeView控件。 -
In the Design mode, move the mouse pointer over the
TreeViewcontrol until a small arrow icon appears in the top-right corner. Click on this arrow to open the TreeView Tasks menu, as shown in the following figure:![Getting ready]()
从TreeView Tasks菜单中,选择Show Lines复选框来显示节点连接。 接下来,点击Edit Nodes链接,打开TreeView Node Editor对话框。 将父节点和子节点添加到控件中,如下面的屏幕截图所示的。 对于显示部门的节点,更新Text和Value属性。 对于显示 employee 的节点,更新Text、Value和ImageUrl属性。 员工的头像照片将从ImageUrl属性中显示。 添加节点后,点击OK按钮:
![Getting ready]()
-
这将为
TreeView控件生成以下标记: -
添加一个
images文件夹到项目中,添加所需的个人资料照片到文件夹中。
怎么做……
在页面的script块中包含以下 jQuery 代码:
<script type="text/javascript">
$(document).ready(function () {
$("#<%=TreeView1.ClientID%> a").on({
mouseover: function () {
$(this).find("img[src$='png']").animate({ width: "64px", height: "64px" }, "slow", "linear");
},
mouseout: function () {
$(this).find("img[src$='png']").stop().animate({ width: "24px", height: "24px" }, "slow", "linear");
}
});
});
</script>
How it works…
树视图控件上的动画的工作原理如下:
-
在运行时,
TreeView控件为树的每个节点生成<a>元素。 为了放大员工的图片,我们将mouseover和mouseout事件的事件处理程序附加到TreeView控件内的<a>元素上,如下所示: -
在
mouseover的事件处理程序中,首先找到以.png扩展结束的图像元素。 这是为了确保展开(+)和折叠(-)图像不会动画。 其次,应用自定义动画将图像的width和height分别增加到 64 像素。 动画时长为slow,缓动为linear:$(this).find("img[src$='png']").animate({ width: "64px", height: "64px" }, "slow", "linear"); -
In the event handler for
mouseout, find the image element that ends with the.pngextension. Then, stop any existing animations using thestopmethod, and apply a custom animation to reduce thewidthandheightto the original dimensions, that is, 24 px each. The duration of the animation isslowand the easing islinear:$(this).find("img[src$='png']").stop().animate({ width: "24px", height: "24px" }, "slow", "linear");注意事项
也可以用
swing代替linear。 只需将mouseover和mouseout事件处理程序中的linear更新为swing。
还有更多的…
缓动是在动画过程中控制不同点的动画速度的一种机制。 jQuery 提供了两个内置的简化方法:linear和swing。 要添加高级效果,可以使用 jQuery UI 库。 jQuery UI 是一个 JavaScript 库,它提供了许多在网站上即插即用的实用程序。 它提供了小部件,比如选项卡、手风琴、进度条、滑动条等等,以及视觉效果,比如弹跳、爆炸、彩色动画等等,还有许多其他功能。
在前面的例子中,让我们通过以下步骤来使用 jQuery UI 的easeOutBounce效果:
-
从http://jqueryui.com/download或 NuGet 包管理器中下载 jQuery UI。 要使用 NuGet 包管理器,请执行Tools|NuGet 包管理器|Manage NuGet Packages for Solution。
-
This will open up the NuGet Package Manager screen. Search for
jQuery.UI.Effects.Core, and click on the Install button:![There's more…]()
这将下载
jquery.effects.core.js和jquery.effects.core.min.js到Scripts文件夹。 -
Next, search for
jQuery.UI.Effects.Bounce, and click on the Install button:![There's more…]()
这将下载
jquery.effects.bounce.js和jquery.effects.bounce.min.js到Scripts文件夹。 -
现在,在 web 表单中包含前面两个库的调试版本如下:
-
In the jQuery code written earlier, update the easing from
linear/swingtoeaseOutBounce, as shown here.对于
mouseover事件,运行以下代码:$(this).find("img[src$='png']").animate({ width: "64px", height: "64px" }, "slow", "easeOutBounce");对于
mouseout事件,运行以下代码:$(this).find("img[src$='png']").stop().animate({ width: "24px", height: "24px" }, "slow", "easeOutBounce"); -
保存并运行页面,以查看当鼠标指针移动到头像照片上和移出头像照片时,头像照片上的弹跳效果。
参见 also
动画 AdRotator 控件配方的 alt 文本
在 Panel 控件中创建滚动文本
可以使用 jQuery 实现的有趣的文本动画中的一个是创建滚动文本。 这个动画有许多应用,比如新闻滚动条、股票报价报价器等等。 在本演示中,让我们将这种类型的动画应用于Panel控件中的文本内容。 我们还将演示如何使用.animate()方法的回调函数参数连续循环动画效果。 本例中使用的结构如下:
构造
|
类型
|
描述
|
| --- | --- | --- |
| $("#identifier") | jQuery 选择器 | 这将使用其 ID 选择一个元素 |
| .animate() | jQuery 方法 | 这将对指定的 CSS 属性执行自定义动画 |
| .css() | jQuery 方法 | 这将获取第一个匹配元素的 CSS 属性,或者为每个匹配元素设置一个或多个 CSS 属性 |
| left | CSS 属性 | 这是一个元素的左边界相对于其包含元素的左边界的位置 |
准备
按照以下步骤在 Panel 控件中创建滚动文本:
-
We will create a web page with a
Panelcontrol and some text content. The text content will be initially positioned toward the right of the containing panel and will be animated to move toward the left, as shown in the following two screenshots:![Getting ready]()
![Getting ready]()
文本从视图中取出后,它将再次从右边重新启动。 这个过程将在一个循环中执行。
-
让我们通过创建一个新的ASP 开始.NET Web 应用项目在 Visual Studio 中使用空的模板并将其命名为
Recipe5(或其他合适的名称)。 -
向项目中添加一个
Scripts文件夹,并将 jQuery 库文件添加到该文件夹中。 -
添加一个新的 web 表单,并在表单中包含 jQuery 库。
-
进入工具箱|Standard,将两个嵌套的
Panel控件添加到窗体中,如下所示。 注意,滚动文本被放置在内部的Panel控件中:<asp:Panel ID="pnlContainer" runat="server"> <asp:Panel ID="pnlScollingText" runat="server"> This is some scrolling text to be displayed. </asp:Panel> </asp:Panel> -
Add the following styles to the respective
Panelcontrols:<style type="text/css"> #pnlContainer { color:white; background-color:black; font-family:'Arial Narrow', Arial, sans-serif; font-size: 20px; font-variant:small-caps; padding:5px; width:500px; height:30px; white-space:nowrap; } #pnlScollingText{ position:absolute; left:500px; } </style>注意,在前面声明的样式中,外部的
Panel控件的width是 500px。 因此,内部Panel控件的left位置被初始化为 500px,也就是说,内部Panel控件的左边界位于外部Panel控件左边界的右侧 500px。 换句话说,文本位于外部Panel控件的右边缘。
怎么做……
将下面的 jQuery 代码添加到页面的script块中:
<script type="text/javascript">
$(document).ready(function () {
loopAnimation();
function loopAnimation() {
$("#<%=pnlScollingText.ClientID%>").css("left", "500px");
$("#<%=pnlScollingText.ClientID%>").animate({ left: "-=850px" }, 7000, "linear", loopAnimation);
}
});
</script>
How it works…
滚动文本的工作原理如下:
-
在浏览器中运行页面时,调用
loopAnimation函数: -
在
loopAnimation函数中,内部Panel控件的左侧位置被重置为 500px。 这确保文本总是从外部控件Panel的右边界开始滚动:$("#<%=pnlScollingText.ClientID%>").css("left", "500px"); -
The inner
Panelcontrol is then animated to reduce its left position gradually to a value equal to (width of the outerPanelcontrol + width of the scrolling text), that is, (500 px + approx. 350 px): approximately 850 px. This value can be found by trial and error:$("#<%=pnlScollingText.ClientID%>").animate({ left: "-=850px" }, 7000, "linear", loopAnimation);动画的持续时间设置为
7000ms:文本从右向左滚动需要 7 秒。 缓动设置为linear。 需要注意的是,loopAnimation函数是作为参数传递给回调函数值的。 这确保动画连续循环,并且函数在每个动画结束时调用自己。
参见 also
动画标签控件来创建数字时钟配方
使用面板控件创建垂直手风琴菜单
这个例子演示了使用Panel控件的滑动动画。 我们将创建一个垂直手风琴菜单,每次只允许一个主菜单项展开。 本例中使用的构造如下:
构造
|
类型
|
描述
|
| --- | --- | --- |
| $("#identifier") | jQuery 选择器 | 这将使用其 ID 选择一个元素。 |
| $(".class") | jQuery 选择器 | 它匹配指定 CSS 类的所有元素。 |
| $(this) | jQuery 对象 | 它引用当前 jQuery 对象。 |
| click | jQuery 的事件 | 当您单击一个元素时,它就会触发。 它对应于 JavaScript 单击事件。 |
| event.stopPropagation() | jQuery 方法 | 这可以防止事件在 DOM 树中冒泡。 |
| .find() | jQuery 方法 | 这将查找与筛选器匹配的所有元素。 |
| .hide() | jQuery 方法 | 这将隐藏匹配的元素。 |
| .is() | jQuery 方法 | 如果匹配的元素满足给定条件,则返回一个布尔值。 |
| .on() | jQuery 事件绑定 | 这将一个或多个事件的事件处理程序附加到匹配的元素。 |
| .slideDown() | jQuery 方法 | 这将显示带有下载幻灯片运动的元素。 |
| .slideUp() | jQuery 方法 | 这将以向上滑动的方式隐藏元素。 |
| :visible | jQuery 选择器 | 这将选择可见的元素,即宽度或高度为> 0 的元素。 |
准备
按照的步骤创建垂直手风琴菜单:
-
We will create a web page with the main menu items, as shown in the following screenshot:
![Getting ready]()
当你点击任何一个主菜单项时,它会以滑动动画的形式展开显示相应的子菜单项,如下图所示:
![Getting ready]()
当您单击任何其他主菜单项时,以前展开的子菜单向上滑动(即折叠),而新的子菜单向下滑动(即展开)。
-
让我们通过创建新的ASP 开始.NET Web 应用项目在 Visual Studio 中使用空模板,并将其命名为
Recipe6(或其他合适的名称)。 -
在项目中创建一个
Scripts文件夹,并将 jQuery 库文件添加到项目中。 -
创建一个新的 web 表单,并将 jQuery 库包含在 web 表单中。
-
在表单中添加以下标记:
<table id="tblMenu" class="mainmenu"> <tr> <td> <img src="images/home.png" />Home <asp:Panel runat="server" CssClass="submenu"> <ul> <li>Configure Dashboard</li> <li>Logout</li> </ul> </asp:Panel> </td> </tr> <tr> <td> <img src="images/accounts.png" />User Accounts <asp:Panel runat="server" CssClass="submenu"> <ul> <li>Create Account</li> <li>Edit / View Accounts</li> <li>Monitor Account</li> </ul> </asp:Panel> </td> </tr> <tr> <td> <img src="images/reports.png" />Reports <asp:Panel runat="server" CssClass="submenu"> <ul> <li>Account Usage</li> <li>Activity Log</li> <li>Account Specific</li> </ul> </asp:Panel> </td> </tr> <tr> <td> <img src="images/settings.png" />Settings <asp:Panel runat="server" CssClass="submenu"> <ul> <li>Update Profile</li> <li>Change Password</li> </ul> </asp:Panel> </td> </tr> </table> -
创建一个
images文件夹,并将主菜单项所需的映像文件添加到这个文件夹中。 -
若要在主菜单项中的图像和文本之间添加间距,请在页面中包含以下样式:
img{ padding-right:5px; } -
为主菜单项添加以下样式:
.mainmenu{ cursor:pointer; width:250px; background-color:lightgray; font-variant:small-caps; font-size:20px; font-family:Arial, sans-serif; font-weight:700; padding:0px; } -
为子菜单项添加以下样式:
.submenu{ color:blue; background-color:lightblue; padding-top:3px; padding-bottom:2px; } .submenu ul{ width:100%; padding-left:3px; list-style-type:none; }
怎么做……
在页面的script块中包含以下 jQuery 代码:
<script type="text/javascript">
$(document).ready(function () {
$(".submenu").hide();
$("#tblMenu").on("click", "tr", function () {
$(".submenu").slideUp("slow");
var submenuPanel = $(this).find(".submenu");
if (!$(submenuPanel).is(":visible"))
$(submenuPanel).slideDown("slow");
});
$(".submenu").on("click", "li", function (evt) {
evt.stopPropagation();
});
});
</script>
How it works…
垂直手风琴菜单的工作原理如下:
-
当页面在浏览器中加载时,所有的子菜单面板使用 CSS 子菜单项选择器隐藏,如下所示:
-
click事件的事件处理程序附加到包含主菜单项的容器表。 事件的目标元素是表行:$("#tblMenu").on("click", "tr", function () {…}); -
由于一次只能看到一个子菜单,前面的事件处理程序将使用滑动动画折叠任何可见的子菜单面板:
$(".submenu").slideUp("slow"); -
然后,
click事件展开单击其主菜单项的子菜单面板。 要确定需要显示的子菜单面板,使用 CSS 选择器对当前对象:var submenuPanel = $(this).find(".submenu"); -
如果所需的子菜单面板已经可见,则无需执行任何操作。 但是,如果它是不可见的,我们需要使用滑动动画来显示它:
-
子菜单项实际上是列表项。 为了防止子菜单项触发展开/折叠菜单,我们对列表项使用
.stopPropagation()方法。 这将防止事件在 DOM 树中冒泡:$(".submenu").on("click", "li", function (evt) { evt.stopPropagation(); });
参见 also
动画菜单控件配方
显示/隐藏带有爆炸效果的 GridView 控件
jQuery UI 库提供了许多有趣的效果,可以很容易地应用在 ASP 上。 网网站。 在前面的食谱中,我们已经看到了将bounce应用于图像时的效果。 在这个特定的例子中,我们将使用另一个称为explode的效果,并将其应用于GridView对照。 本例中使用的构造如下:
构造
|
类型
|
描述
|
| --- | --- | --- |
| $("#identifier") | jQuery 选择器 | 这将使用其 ID 选择一个元素。 |
| event.preventDefault() | jQuery 方法 | 这将防止触发事件的默认动作。 |
| explode | jQuery UI 的效果 | 这将在隐藏或显示元素时按指定的块数拆分元素。 |
| .hide() | jQuery 方法 | 这将隐藏匹配的元素。 |
| .is() | jQuery 方法 | 如果匹配的元素满足给定条件,则返回一个布尔值。 |
| pieces | 属性的 jQuery UI 爆炸效果 | 这是要爆炸的碎片数。 其默认值为 9。 |
| .show() | jQuery 方法 | 这会显示匹配的元素。 |
| .val() | jQuery 方法 | 返回第一个匹配元素的值,或者设置每个匹配元素的值。 |
| :visible | jQuery 选择器 | 这将选择可见的元素,即宽度或高度为> 0 的元素。 |
准备
按照以下步骤在窗体上设置一个数据驱动的 GridView 控件:
-
Let's create a page that consists of a
GridViewcontrol that displays theEmployeedata from the Northwind database, as shown in the following screenshot:![Getting ready]()
点击页面顶部的Hide GridView按钮,
GridView控件逐渐隐藏,效果如下:![Getting ready]()
动画被应用,直到
GridView控件完全隐藏,如下图所示:![Getting ready]()
按钮现在变为显示 GridView。 当您单击该按钮时,
GridView控件将使用相同的效果逐渐显示出来。 -
要开始,创建一个新的ASP.NET Web 应用项目在 Visual Studio 中使用空模板,并将其命名为
Recipe7(或其他合适的名称)。 -
在项目中创建一个
Scripts文件夹,并将 jQuery 库文件添加到该文件夹中。 -
添加一个新的 web 表单到项目中,并在表单中包含 jQuery 库。
-
通过导航到工具箱|Data,在窗体上拖放
GridView控件。 -
In the Design mode, move the mouse pointer over the
GridViewcontrol until a small arrow icon appears in the top-right corner. Click on this arrow to open the GridView Tasks menu, as shown in the following figure:![Getting ready]()
-
From the preceding menu, select <New data source…> from the Choose Data Source drop-down menu. This will open the Data Source Configuration Wizard, as shown in the following screenshot. Select SQL, and complete the wizard to connect to the Northwind database running on MS SQL Server:
![Getting ready]()
在数据源配置向导中配置Select Statement选项时,选择
Employees表,并选择EmployeeID、LastName、FirstName列:![Getting ready]()
注意事项
请注意,本书中所有数据库驱动的示例都使用 Windows 身份验证。 因此,在 MS SQL Server 中,给 windows 帐户访问 Northwind 数据库的权限是很重要的。
-
To style the
GridViewcontrol, you can open the GridView Tasks menu once again, and click on Auto Format. Choose the required formatting scheme, and click on Apply to format theGridViewcontrol:![Getting ready]()
-
另外,通过导航到工具箱|Standard,将一个
Button控件添加到窗体中。 此按钮将用于根据需要隐藏/显示GridView控件。 -
因此,表单的标记如下:
```
<asp:Button ID="btnShowHide" runat="server" Text="Hide GridView" />
<br /><br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="EmployeeID" DataSourceID="SqlDataSource1" AllowPaging="True" CellPadding="3" GridLines="Vertical" BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="1px">
<AlternatingRowStyle BackColor="#DCDCDC" />
<Columns>
<asp:BoundField DataField="EmployeeID" HeaderText="EmployeeID" InsertVisible="False" ReadOnly="True" SortExpression="EmployeeID" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
</Columns>
<FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
<HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<RowStyle BackColor="#EEEEEE" ForeColor="Black" />
<SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#0000A9" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#000065" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" SelectCommand="SELECT [FirstName], [LastName], [EmployeeID] FROM [Employees]"></asp:SqlDataSource>
```
- To use the
explodeeffect, we need to download the necessary jQuery UI files by navigating to Tools | NuGet Package Manager | Manage NuGet Packages for Solution. In the Nuget Package Manager screen, as shown in the following screenshot, search forjQuery.UI.Effects.Core, and click on Install. This will add both the debug and release versions:jquery.effects.core.jsandjquery.effects.core.min.jsto theScriptsfolder:

- Next, search for
jQuery.UI.Effects.Explode, and click on Install. This will addjquery.effects.explode.jsandjquery.effects.explode.min.jsto theScriptsfolder:

- 在 Web 窗体中包括
jQuery.UI.Effects.Core和jQuery.UI.Effects.Explode的调试版本,如下所示:
怎么做……
在页面的script块中包含以下 jQuery 代码:
<script type="text/javascript">
$(document).ready(function () {
$("#<%=btnShowHide.ClientID%>").click(function (evt) {
evt.preventDefault();
if ($("#GridView1").is(":visible")) {
$("#GridView1").hide("explode", { pieces: 100 }, 5000);
$("#<%=btnShowHide.ClientID%>").val("Show GridView");
}else {
$("#GridView1").show("explode", { pieces: 100 }, 5000);
$("#<%=btnShowHide.ClientID%>").val("Hide GridView");
}
});
});
</script>
How it works…
GridView 控件上的爆炸效果如下所示:
-
当页面在浏览器中启动时,一个事件处理程序被附加到
Button控件的单击事件,如下所示: -
在这个事件处理程序中,首先阻止
Button控件的默认行为,即阻止页面在Button上提交:evt.preventDefault(); -
接下来,我们检查
GridView控件是否可见。 如果它是可见的,那么使用 jQuery UI 的explode效果将其逐渐隐藏。pieces个数设置为100,动画时长设置为5000ms;GridView控制将爆炸成 100 个碎片并在 5 秒内逐渐消失。Button控件的Text属性也相应更新:if ($("#GridView1").is(":visible")) { $("#GridView1").hide("explode", { pieces: 100 }, 5000); $("#<%=btnShowHide.ClientID%>").val("Show GridView"); } -
如果
GridView控件不可见,则使用 jQuery UI 的爆炸效果逐渐显示出来。pieces的数量再次设置为100,动画的持续时间设置为5000ms;GridView控制装置由 100 个部件组成,5 秒内即可显示。Button控件的Text属性也相应更新:else { $("#GridView1").show("explode", { pieces: 100 }, 5000); $("#<%=btnShowHide.ClientID%>").val("Hide GridView"); }
参见 also
树视图控件配方中的动画图像
六、在 ASP.NET 中使用图形
本章探讨如何使用 jQuery 在 ASP 中嵌入图形.NET 网站和 MVC。 本章将介绍以下食谱:
- 在图像上创建聚光灯效果
- 鼠标悬停时缩放图像
- 创建图像滚动条
- 使用 z-index 属性构建一个图片库
- 使用 ImageMap 控件构建一个相册
- 使用图像在菜单控件中创建效果
- 创建一个 5 星级的评级控件
- 在 MVC 中预览图像上传
简介
Web 完全是关于内容和向观众展示内容。 内容的视觉表现和交互性以及用户友好性是构建网站时需要考虑的重要因素。 在网页内容中使用图形增加了其视觉吸引力,并增强了最终用户的体验。 图形的例子包括图像、动画 gif、flash、图表、图像按钮等等。
jQuery 简化了将图形集成到 web 内容的过程。 它提供了在 web 元素上创建效果和动画的实用程序。 可以方便地附加事件处理程序,并且客户端处理可以避免往返于服务器,从而提高性能。
使用 jQuery, ASP.NET 服务器控件(例如Image、ImageButton和ImageMap可以通过效果、动画和事件处理程序进行增强。 简单的 HTML 元素,比如图像元素,也可以使用 jQuery 进行操作。 这种方法在 MVC 应用中很有用,因为 MVC 使用 HTML 元素而不是服务器控件。
在本章中,我们将看看 jQuery 在图形元素中的一些常见用法。
在图像上创建聚光灯效果
通常需要在焦点项目上创建一个聚光灯,例如文本或网页上的任何图形元素,以吸引对该项目的注意。 在这个食谱中,让我们看看如何在一组图像上创建这样的效果。 下表总结了本例中使用的结构:
|构造
|
类型
|
描述
|
| --- | --- | --- |
| $("#identifier") | jQuery 选择器 | 这将根据元素的 ID 选择一个元素 |
| $("html_tag") | jQuery 选择器 | 这将选择具有指定 HTML 标记的所有元素 |
| $(this) | jQuery 对象 | 它引用当前 jQuery 对象 |
| .addClass() | jQuery 方法 | 这会将指定的 CSS 类添加到每个匹配的元素中 |
| .css() | jQuery 方法 | 这将获取第一个匹配元素的 style 属性,或者设置每个匹配元素的 style 属性 |
| .hover() | jQuery 事件绑定 | 这绑定了mouseover和mouseout事件的事件处理程序 |
| .removeClass() | jQuery 方法 | 这将从每个匹配的元素中删除指定的 CSS 类 |
准备
让我们构建一个带有聚焦效果图片的网页:
-
Let's create a web page with a collection of image controls arranged in a grid format, as shown in the following screenshot:
![Getting ready]()
-
On moving the mouse pointer over any image in the grid, the focused item receives a spotlight with the remaining items fading out, as shown in this screenshot:
![Getting ready]()
-
要创建此应用,请启动ASP.NET Web 应用项目在 Visual Studio 中使用空模板,并将其命名为
Recipe1(或任何其他合适的名称)。 -
将 jQuery 库添加到的
Scripts文件夹中。 向images文件夹中添加一些示例图像。 -
添加一个 web 表单到项目中,并在表单中包含 jQuery 库。
-
将以下标记添加到页面中,以创建一个具有两行三列的表。 在每个表单元格中添加一个
Image控件: -
Include the following styles on the page to set the display dimensions of the images and padding/margins for the table element:
<style type="text/css"> #container img { width: 213px; height: 142px; display: block; } #container table { padding: 1px; } #container td { padding: 0px; margin: 0px; } .highlight { border-color: #000000; border-width: 1px; border-style: solid; } </style>前面定义的高亮 CSS 类将用于给聚焦的图像附加边框。
怎么做……
添加以下 jQuery 代码到页面的<script>块:
<script type="text/javascript">
$(document).ready(function() {
$("#container img").hover(
function() {
$("#container img").css("opacity", "0.2");
$(this).css("opacity", "1");
$(this).addClass("highlight");
},
function() {
$("#container img").css("opacity", "1");
$(this).removeClass("highlight");
});
});
</script>
How it works…
对图像的聚焦效果实现如下:
-
用Ctrl+S保存页面,然后用F5运行。 这将在浏览器窗口中启动页面,图像将显示在网格中。
-
使用
.hover()方法将mouseover和mouseout事件处理程序绑定到图像上,如下所示: -
On moving the mouse pointer over any image, the
mouseoverevent handler is triggered. This handler, first of all, fades all images in the grid by setting theiropacityto0.2:$("#container img").css("opacity", "0.2");只有聚焦后的图像,即有聚光灯的图像,通过将其
opacity设置为1而完全不透明:$(this).css("opacity", "1");通过添加
highlightCSS 类,一个实心边框也应用于聚焦图像:$(this).addClass("highlight"); -
On moving the mouse pointer outwards from the spotlight, the
mouseoutevent handler is triggered. This event handler restores theopacityof all images in the grid to1:$("#container img").css("opacity", "1");它也从聚焦图像中删除了实边界:
$(this).removeClass("highlight");
参见 also
使用图像在菜单控件配方中创建效果
鼠标悬停时缩放图像
一些应用需要在特定位置缩放或放大图像。 在这个食谱中,我们将在鼠标进入图像的位置缩放图像。 本例中使用的构造如下:
|构造
|
类型
|
描述
|
| --- | --- | --- |
| $("#identifier") | jQuery 选择器 | 这将根据元素的 ID 选择一个元素。 |
| $(this) | jQuery 对象 | 它引用当前 jQuery 对象。 |
| .css() | jQuery 方法 | 这将获取第一个匹配元素的 style 属性,或者设置每个匹配元素的 style 属性。 |
| height | CSS 属性 | 这是元素的高度。 |
| left | CSS 属性 | 这是元素左边缘的位置。 对于绝对定位的元素,它指示左边缘相对于父元素的位置。 |
| mousemove | jQuery 的事件 | 当鼠标指针移动到元素内部时,就会触发此操作。 它对应于 JavaScript 的mousemove事件。 |
| mouseout | jQuery 的事件 | 当鼠标指针离开一个元素时触发。 它对应于 JavaScript 的mouseout事件。 |
| mouseover | jQuery 的事件 | 当鼠标指针进入一个元素时触发。 它对应于 JavaScript 的mouseover事件。 |
| .on() | jQuery 事件绑定 | 这将为一个或多个事件附加一个事件处理程序到匹配的元素。 |
| pageX | jQuery 事件属性 | 这将返回鼠标指针相对于文档左边缘的位置。 |
| pageY | jQuery 事件属性 | 这将返回鼠标指针相对于文档顶部边缘的位置。 |
| .prop(propertyName)或.prop(propertyName, value) | jQuery 方法 | 这将为第一个匹配的元素返回指定属性的值,或者为所有匹配的元素设置指定属性的值。 |
| top | CSS 属性 | 这是元素的上边缘的位置。 对于绝对定位的元素,它指示上边缘相对于父元素的位置。 |
| width | CSS 属性 | 这是元素的宽度。 |
准备
让我们构建一个页面,在鼠标悬停时缩放图像:
-
In this example, we will create a page with a single image control, as shown in the following screenshot:
![Getting ready]()
当将鼠标移动到图像上时,它将在鼠标指针第一次进入图像的位置缩放,如下所示:
![Getting ready]()
将鼠标指针移动到图像上,可以使放大的图像沿鼠标方向滚动。
-
要开始,请使用ASP 的空模板.NET Web 应用项目,并将项目命名为
Recipe2(或任何其他合适的名称)。 -
将 jQuery 库添加到项目中的
Scripts文件夹中。 在images文件夹中包含一个测试映像。 -
创建一个 web 表单,并在表单中包含 jQuery 库。
-
通过导航到工具箱|Standard到
container``div元素,添加Image控件,创建以下标记: -
要设置
container``div的尺寸,请在页面中包含以下 CSS:<style type="" text/css ""> #container { width: 640px; height: 480px; overflow: hidden; position: relative; } #imgSample { position: absolute; } </style> -
Note that the
positionof thecontainerdivis set torelativewhile thepositionof theImagecontrol is set toabsolute. To be able to move an absolutely positioned child element within a parent element, the parent element should be relatively positioned.container``div的overflow被设置为hidden,因此放大的图像被保留在其中,并且对最终用户隐藏任何溢出。 图像可以滚动查看隐藏区域。
怎么做……
将下面的 jQuery 代码添加到页面的<script>块中:
<script type="text/javascript">
$(document).ready(function() {
$("#<%=imgSample.ClientID%>").on("mouseover", function(evt) {
var zoomIndex = 2;
var iWidth = $(this).prop("width");
var iHeight = $(this).prop("height");
var newWidth = iWidth * zoomIndex;
var newHeight = iHeight * zoomIndex;
var posX = evt.pageX;
var posY = evt.pageY;
$(this).css({
width: newWidth,
height: newHeight,
left: -posX,
top: -posY
});
});
$("#<%=imgSample.ClientID%>").on("mousemove", function(evt) {
var posX = evt.pageX;
var posY = evt.pageY;
$(this).css({
left: -posX,
top: -posY
});
});
$("#<%=imgSample.ClientID%>").on("mouseout", function() {
$(this).css({
width: "640px",
height: "480px",
left: 0,
top: 0
});
});
});
</script>
How it works…
鼠标悬停时图像的缩放实现如下:
-
jQuery 代码使用以下代码将
mouseover,mousemove和mouseout事件的事件处理程序附加到图像控件: -
In the
mouseoverevent handler, the image is enlarged and the position of the image is shifted so that the image appears to zoom at the location where the mouse pointer enters the image. The amount of zoom is determined by thezoomIndexvariable, as follows:var zoomIndex = 2;这里,图像被放大到原来尺寸的两倍。
使用
.prop()方法获取图像的原始尺寸,使用zoomIndex变量计算新尺寸:var iWidth = $(this).prop("width"); var iHeight = $(this).prop("height"); var newWidth = iWidth * zoomIndex; var newHeight = iHeight * zoomIndex;鼠标指针的x和y坐标由
evt事件变量给出的mouseover事件的pageX和pageY属性决定:var posX = evt.pageX; var posY = evt.pageY;然后使用
css()方法设置图像的新尺寸和位置。 图像的左侧和顶部位置发生了改变,因此它会在鼠标指针的位置上移动并缩放。 我们可以使用任何常量值来进行移位,也可以使用posX和posY值,如下代码所示:$(this).css({ width: newWidth, height: newHeight, left: -posX, top: -posY }); -
In the
mousemoveevent handler, the enlarged image is scrolled in the direction of the mouse pointer. This is done by first retrieving the x and y coordinates of the mouse pointer:var posX = evt.pageX; var posY = evt.pageY;然后使用
css()方法中前面的值更新图像的左侧和顶部位置:$(this).css({ left: -posX, top: -posY }); -
In the
mouseoutevent handler, the image is reset to its original dimension and position using the.css()method:$(this).css({ width: "640px", height: "480px", left: 0, top:0 });因此,图像缩小到其原始大小并绝对定位,即在
containerdiv 的left等于0和top等于0处。
提示
变量 T0 控制当前代码示例中的缩放量。 我们用了zoomIndex = 2。 您可以在脚本中使用不同的zoomIndex值进行实验。 或者,允许用户通过提供DropDownList控件或任何其他合适的控件来输入放大倍数。
参见 also
使用 z-index 属性创建图片库
创建图像滚动条
这个配方演示了通过动画化父容器元素的左侧位置,将一系列图像水平地向左或向右滚动。 本例中使用的构造总结如下:
|构造
|
类型
|
描述
|
| --- | --- | --- |
| $("#identifier") | jQuery 选择器 | 这将根据元素的 ID 选择一个元素。 |
| .animate() | jQuery 方法 | 这将对指定的 CSS 属性执行自定义动画。 |
| click | jQuery 的事件 | 当您单击一个元素时,它就会触发。 它对应于 JavaScript 的click事件。 |
| event.preventDefault() | jQuery 方法 | 这将防止触发事件的默认动作。 |
| left | CSS 属性 | 这是元素左边缘的位置。 |
| .on() | jQuery 事件绑定 | 这将一个事件处理程序附加到一个或多个事件的匹配元素。 |
| z-index | CSS 属性 | 这是元素的 z 轴顺序。 当元素重叠时,具有较高 z 轴次序的元素会出现在具有较低 z 轴次序的元素之上。 |
准备
让我们通过以下步骤创建一个图像滚动条页面:
-
让我们开始创建一个新的ASP.NET Web 应用项目在 Visual Studio 中使用空模板,并将其命名为
Recipe3(或任何其他合适的名称)。 -
向项目中添加一个
Scripts文件夹,并将 jQuery 库包含在此文件夹中。 -
在项目的
images文件夹中添加一些示例图像。 -
添加一个新的 web 表单,并在表单中包含 jQuery 库。
-
Include the following markup on the form:
<div id="container"> <asp:ImageButton ID="btnLeftScroll" runat="server" ImageUrl="~/images/arrow-left-icon.png" /> <asp:ImageButton ID="btnRightScroll" runat="server" ImageUrl="~/images/arrow-right-icon.png" /> <table id="tblImages"> <tr> <td> <asp:Image ID="imgSample1" runat="server" ImageUrl="~/images/image1.jpg" Width="640" Height="425" /> </td> <td> <asp:Image ID="imgSample2" runat="server" ImageUrl="~/images/image2.jpg" Width="640" Height="427" /> </td> <td> <asp:Image ID="imgSample3" runat="server" ImageUrl="~/images/image3.JPG" Width="640" Height="360" /> </td> <td> <asp:Image ID="imgSample4" runat="server" ImageUrl="~/images/image4.JPG" Width="640" Height="427" /> </td> <td> <asp:Image ID="imgSample5" runat="server" ImageUrl="~/images/image5.JPG" Width="640" Height="427" /> </td> <td> <asp:Image ID="imgSample6" runat="server" ImageUrl="~/images/image6.JPG" Width="640" Height="427" /> </td> <td> <asp:Image ID="imgSample7" runat="server" ImageUrl="~/images/image7.JPG" Width="640" Height="427" /> </td> </tr> </table> </div>这个将创建一个由
table组成的container``div元素,该元素有 7 列 1 行。 每个表格单元格包含一个Image控件。 这些图像可能/可能没有不同的尺寸。两个
ImageButton控件分别用于向左和向右滚动。 这些ImageButton控件使用 CSS 叠加在显示的图像之上。 -
Apply the following styles to the preceding markup:
<style type="text/css"> #container{ position:relative; overflow:hidden; width:640px; height:427px; vertical-align:central; margin:0; } #tblImages{ position:absolute; padding:0px; margin:0px; border-collapse:collapse; } #tblImages td{ padding:0px; } #btnLeftScroll{ position:absolute; left:10px; top:200px; z-index:2; width:48px; height:48px; } #btnRightScroll{ position:absolute; left:580px; top:200px; z-index:2; width:48px; height:48px; } </style>注意事项
注意的
position``container``div设置为relative的position表包含的图像设置为absolute,container内的表可以移动 div。左边和右边的position按钮也将【显示】的z-index``2的按钮出现在顶部显示的图像。 -
Thus, the page will appear, as shown in the following screenshot:
![Getting ready]()
点击左键后,序列向左移动,如下图所示:
![Getting ready]()
类似地,单击右按钮后,序列向右滚动,如所示:
![Getting ready]()
怎么做……
添加以下 jQuery 代码到页面的<script>块:
<script type="text/javascript">
$(document).ready(function() {
var containerWidth = 640;
var totalImgWidth = 640 * 7;
var leftEdgePos = 0;
var rightEdgePos = totalImgWidth - 50;
$("#<%=btnLeftScroll.ClientID%>").on("click", function(evt) {
evt.preventDefault();
scrollLeft();
});
$("#<%=btnRightScroll.ClientID%>").on("click", function(evt) {
evt.preventDefault();
scrollRight();
});
function scrollLeft() {
if (rightEdgePos > containerWidth) {
rightEdgePos -= 200;
leftEdgePos -= 200;
$("#tblImages").animate({
left: '-=200px'
}, 1500, "linear");
}
}
function scrollRight() {
if (leftEdgePos < 0) {
leftEdgePos += 200;
rightEdgePos += 200;
$("#tblImages").animate({
left: '+=200px'
}, 1500,
"linear");
}
}
});
</script>
How it works…
图像滚动条的工作原理如下:
-
用Ctrl+S保存页面,然后用F5运行。 这将在浏览器窗口中启动应用。 在加载时,页面将按顺序显示第一个图像以及左右箭头按钮。 要滚动,请单击相应的按钮。 注意,当向右滚动时,一旦第一个图像的左边缘与容器 div 的左边缘重合,滚动就会停止。 类似地,当向左滚动时,当最后一个图像的右边缘与容器 div 的右边缘重合时,滚动将停止。
-
.aspx标记由container``div组成,其宽度为640px,高度为427px。 它的position被定义为relative,这样子元素就可以完全定位在其中。overflow被定义为hidden,因此每次我们只能查看子元素的640px *427px 窗口。 -
The
containerdivhas a childtableelement with an ID equal totblImages. This table contains the images arranged column-wise. These are the images that we need to scroll. The table is absolutely positioned so that it's left edge can be animated. At any time, the user will see only the CONTAINER DIV, that is, the blue shaded area in the following diagram, and the table will scroll in the background:![How it works…]()
-
In the jQuery script, the
containerdivwidth is kept constant at640px:var containerWidth = 640;由于有 7 张图片,每张图片的宽度为
640px,所以可以确定总的表宽,如下所示:var totalImgWidth = 640 * 7;tblImages的左边缘的位置被初始化为与容器 div 的左边缘重合:
var leftEdgePos = 0;tbimagages的右边缘的位置被初始化为与表的总宽度减去
50px 相一致,以防止右边缘滚动超过容器 div 的右边缘:var rightEdgePos = totalImgWidth - 50; -
事件的事件处理程序附加到每个
ImageButton控件,即左按钮和右按钮。 左键调用scrollLeft函数,右键调用scrollRight函数。 两个事件处理程序都调用event.preventDefault()方法来防止页面回发: -
让我们以为例,看看
scrollLeft()函数中发生了什么。 首先,我们需要检查滚动表的右边缘的位置。 如果右边缘位于container``div右边缘的右边,我们可以使表格动起来并将其向左滑动。 对于每次点击左键,我们将在1500ms 中将表格向左移动200px。左右边缘的位置通过200px 调整,如下代码所示:function scrollLeft() { if (rightEdgePos > containerWidth) { rightEdgePos -= 200; leftEdgePos -= 200; $("#tblImages").animate({ left: '-=200px' }, 1500, "linear"); } } -
类似地,在
scrollRight函数中,我们检查滚动表的左边缘位置。 如果左侧边缘位于container``div左侧边缘的左侧,则可以使表格动画并将其向右侧滑动。 每点击一次右按钮,我们就会在1500ms 中将表格向右移动200px,表格的左右边缘位置也会相应地调整200px:
参见 also
在图像上创建聚光灯效果配方
使用 z-index 属性创建相册
照片图库是大多数社交媒体网站上常见的功能。 使用 jQuery 构建这些库的方法有很多种。 在本食谱中,让我们使用 z-index CSS 属性来构建这样一个应用。 下表显示了本例中使用的构造的摘要:
|构造
|
类型
|
描述
|
| --- | --- | --- |
| $("#identifier") | jQuery 选择器 | 这将根据元素的 ID 选择一个元素。 |
| $("html_tag") | jQuery 选择器 | 这将选择具有指定 HTML 标记的所有元素。 |
| $(this) | jQuery 对象 | 它引用当前 jQuery 对象。 |
| click | jQuery 的事件 | 当您单击一个元素时,它就会触发。 它对应于 JavaScript 的click事件。 |
| .css() | jQuery 方法 | 这将获取第一个匹配元素的 style 属性,或者设置每个匹配元素的 style 属性。 |
| .each() | jQuery 方法 | 这将遍历匹配的元素,并为每个元素执行一个函数。 |
| event.preventDefault () | jQuery 方法 | 这将防止触发事件的默认动作。 |
| .length | jQuery 的财产 | 这将返回 jQuery 对象中的元素数量。 |
| .on() | jQuery 事件绑定 | 这将一个事件处理程序附加到一个或多个事件的匹配元素。 |
| parseInt(string) | JavaScript 函数 | 它将字符串转换为整数。 |
| z-index | CSS 属性 | 这是元素的 z 轴顺序。 当元素重叠时,具有较高 z 轴次序的元素会出现在具有较低 z 轴次序的元素之上。 |
准备
按照以下步骤使用 z-index 属性创建一个带有图片库的页面:
-
We aim to create a page that displays one image at a time from a sequence of images. Navigation in the sequence is possible by clicking on the previous and next buttons. The images are displayed in a loop, so clicking on the next button on the last image displays the first image and clicking on the previous button on the first image displays the last image:
![Getting ready]()
-
要创建此图库,请启动新的ASP.NET Web 应用项目在 Visual Studio 中使用空模板,并将其命名为
Recipe4(或任何其他合适的名称)。 -
在项目中创建一个
Scripts文件夹,并将 jQuery 库添加到该文件夹中。 在images文件夹中包含一些示例图像。 -
创建一个新的 web 表单,并在表单中包含 jQuery 库。
-
我们将创建一个包含两行和一列的 HTML
<table>元素。 第一行将有 6 个Image控件,它们通过id = container添加到表格单元格中。 第二行将有两个ImageButton控件用于前一个和下一个图像导航。 因此,向表单添加以下标记:<table><tr><td id="container"> <asp:Image ID="imgSample1" ImageUrl="~/images/image1.jpg" runat="server" /> <asp:Image ID="imgSample2" ImageUrl="~/images/image2.jpg" runat="server" /> <asp:Image ID="imgSample3" ImageUrl="~/images/image3.jpg" runat="server" /> <asp:Image ID="imgSample4" ImageUrl="~/images/image4.jpg" runat="server" /> <asp:Image ID="imgSample5" ImageUrl="~/images/image5.jpg" runat="server" /> <asp:Image ID="imgSample6" ImageUrl="~/images/image6.jpg" runat="server" /> </td></tr> <tr><td> <asp:ImageButton ID="btnPrevious" CssClass="buttonStyle" ImageUrl="~/images/backward.ico" runat="server" ToolTip="View previous photo" /> <asp:ImageButton ID="btnNext" CssClass="buttonStyle" ImageUrl="~/images/forward.ico" runat="server" ToolTip="View next photo"/> </td></tr> </table> -
在页面上包括以下样式,以便设置元素的尺寸和它们各自的位置:
<style type="text/css"> buttonStyle{ width:68px; height:68px; } #container{ position:relative; width:640px; height:425px; } #container img{ position:absolute; top:0px; left:0px; } td{ text-align:center; } </style>
注意事项
注意,容器表单元格的position属性被定义为relative。 这使得它的子元素能够被绝对定位。 它的尺寸保持不变,所有的图片都以这些尺寸显示在画廊中。
怎么做……
将和的 jQuery 代码添加到页面的<script>块中:
<script type="text/javascript">
$(document).ready(function() {
var maxZIndex = $("#container img").length;
var tempZIndex = maxZIndex;
$("#container img").each(function() {
$(this).css("z-index", tempZIndex);
tempZIndex--;
});
$("#<%=btnPrevious.ClientID%>").on("click",
function(evt) {
evt.preventDefault();
$("#container img").each(function() {
var currZIndex = parseInt($(this).css("z-index"));
if (currZIndex == 1)
$(this).css("z-index", maxZIndex);
else
$(this).css("z-index", currZIndex - 1);
});
});
$("#<%=btnNext.ClientID%>").on("click",
function(evt) {
evt.preventDefault();
$("#container img").each(function() {
var currZIndex = parseInt($(this).css("z-index"));
if (currZIndex == maxZIndex)
$(this).css("z-index", 1);
else
$(this).css("z-index", currZIndex + 1);
});
});
});
</script>
How it works…
图片库的作品如下:
-
On launching the page in the browser, the gallery displays the first image in the markup. After clicking on the previous or next button, it navigates to the required images, as shown in the following screenshot:
![How it works…]()
-
In the jQuery code, we assign a
z-indexconstruct to each image, ranging from 1 to the maximum number of images. The image with the highest z-index at any point in time will be displayed in the gallery. To do this, first determine the total number of images:var maxZIndex = $("#container img").length;现在给每个图像元素赋值
z-index,方法是给第一张图像赋值最高的索引,然后对循环中的每个元素递减1:var tempZIndex = maxZIndex; $("#container img").each(function () { $(this).css("z-index", tempZIndex); tempZIndex--; }); -
An event handler is attached to the previous button for the
clickevent, as follows:$("#<%=btnPrevious.ClientID%>").on("click", function (evt) {…});在这个事件处理程序中,首先,我们阻止页面在点击按钮时发回:
evt.preventDefault();然后,各图像元素的
z-index减小1。 如果任何元素的z-index具有最小值,即1,则将其重置为最大值。 这确保了图像在循环中显示; 当你点击上一个按钮时,第一个图像将显示最后一个图像:$("#container img").each(function () { var currZIndex = parseInt($(this).css("z-index")); if (currZIndex == 1) $(this).css("z-index", maxZIndex); else $(this).css("z-index", currZIndex-1); }); -
An event handler is attached to the next button for the
clickevent, as follows:$("#<%=btnNext.ClientID%>").on("click", function (evt) {…});在这个事件处理程序中,页面首先被阻止发回:
evt.preventDefault();每个图像元素的
z-index加1。 如果元素的z-index具有最大值,则将其重置为1。 这确保当你点击 next 按钮时,最后一张图片将显示第一张图片:$("#container img").each(function () { var currZIndex = parseInt($(this).css("z-index")); if (currZIndex == maxZIndex) $(this).css("z-index", 1); else $(this).css("z-index", currZIndex + 1); });
参见 also
使用 ImageMap 控件配方构建相册
使用 ImageMap 控件构建一个相册
由于图库可以使用许多不同的方法来构建,所以让我们利用 ASP.NETImageMap控件中创建图库。 下表列出了本例中使用的构造的摘要:
构造
|
类型
|
描述
|
| --- | --- | --- |
| $("#identifier") | jQuery 选择器 | 这将根据元素的 ID 选择一个元素。 |
| $("html_tag") | jQuery 选择器 | 这将选择具有指定 HTML 标记的所有元素。 |
| [attribute= "value"] | jQuery 选择器 | 这将选择具有指定属性等于"value"字符串的元素。 |
| click | jQuery 的事件 | 当您单击一个元素时,它就会触发。 它对应于 JavaScript 的click事件。 |
| event.preventDefault() | jQuery 方法 | 这将防止触发事件的默认动作。 |
| .hide() | jQuery 方法 | 这将隐藏匹配的元素。 |
| .hover() | jQuery 事件绑定 | 这绑定了mouseover和mouseout事件的事件处理程序。 |
| .on() | jQuery 事件绑定 | 这将一个事件处理程序附加到一个或多个事件的匹配元素。 |
| .prop(propertyName)或.prop(propertyName, value) | jQuery 方法 | 这将为第一个匹配的元素返回指定属性的值,或者为所有匹配的元素设置指定属性的值。 |
| .show() | jQuery 方法 | 这会显示匹配的元素。 |
准备
按照以下步骤用 ImageMap 控件构建页面:
-
创建一个新的ASP.NET Web 应用项目在 Visual Studio 中使用空模板,并将其命名为
Recipe5(或任何其他合适的名称)。 -
添加一个
Scripts文件夹,并将 jQuery 库包含在该文件夹中。 -
在项目中添加一个
images文件夹。 向文件夹中添加一些示例图像。 -
创建一个 web 表单,并在表单中包含 jQuery 库。
-
进入工具箱|Standard,添加一个
ImageMap和两个Image控件到窗体中。ImageMap将用于在相册中显示图像,而Image控件将用于显示左右方向箭头。 -
Define two rectangular hotspots on the
ImageMapcontrol with the dimension50 * 58, assuming that the image is of the dimension680 * 425. The position of the two hotspots is shown in the following image:![Getting ready]()
这可以通过在
.aspx页面中添加以下标记来实现:<div id="container"> <asp:Image ID="imgPrevious" ImageUrl="~/images/Arrows-Back-icon.png" runat="server" /> <asp:Image ID="imgNext" ImageUrl="~/images/Arrows-Forward-icon.png" runat="server" /> <asp:ImageMap ID="imgMap" ImageUrl="~/images/image1.jpg" runat="server"> <asp:RectangleHotSpot HotSpotMode="NotSet" Left="0" Right="50" Top="212" Bottom="270" AlternateText="Previous" /> <asp:RectangleHotSpot HotSpotMode="NotSet" Left="630" Right="680" Top="212" Bottom="270" AlternateText="Next" /> </asp:ImageMap> </div> -
To set the dimensions and positions of the elements, include the following styles on the page:
<style type="text/css"> #container{ position:relative; } #imgMap{ width:680px; height:425px; position:absolute; top:0px; left:50px; } #imgPrevious{ top:212px; left:0px; position:absolute; width:48px; height:48px; } #imgNext{ top:212px; left:750px; position:absolute; width:48px; height:48px; } </style>container``div是相对定位的,而这个div中的所有其他控件是绝对定位的。 -
On launching the browser, the page will display the first image in the gallery, as shown in the following screenshot. On mouseover on the hotspot on the left, the left direction arrow will appear:
![Getting ready]()
同样,将鼠标悬停在右侧热点上,会出现右侧方向箭头,如下图所示:
![Getting ready]()
在下一节中,我们将添加 jQuery 代码,用于在单击相应热点后显示上一张或下一张图像。
怎么做……
将下面的 jQuery 代码添加到的<script>块中:
<script type="text/javascript">
$(document).ready(function() {
var imgArr = ["image1.jpg", "image2.jpg", "image3.jpg",
"image4.jpg", "image5.jpg", "image6.jpg"
];
var minIndex = 0;
var maxIndex = imgArr.length - 1;
var currIndex = 0;
var basePath = "/images/";
$("#<%=imgPrevious.ClientID%>").hide();
$("#<%=imgNext.ClientID%>").hide();
$("map area[title='Previous'").hover(
function() {
$("#<%=imgPrevious.ClientID%>").show();
},
function() {
$("#<%=imgPrevious.ClientID%>").hide();
});
$("map area[title='Next'").hover(
function() {
$("#<%=imgNext.ClientID%>").show();
},
function() {
$("#<%=imgNext.ClientID%>").hide();
});
$("map area[title='Previous'").on("click", function(evt) {
evt.preventDefault();
if (currIndex == minIndex)
currIndex = maxIndex;
else
currIndex--;
var imgPath = basePath + imgArr[currIndex];
$("#<%=imgMap.ClientID%>").prop("src", imgPath);
});
$("map area[title='Next'").on("click", function(evt) {
evt.preventDefault();
if (currIndex == maxIndex)
currIndex = minIndex;
else
currIndex++;
var imgPath = basePath + imgArr[currIndex];
$("#<%=imgMap.ClientID%>").prop("src", imgPath);
});
});
</script>
How it works…
图片画廊作品如下:
-
In the jQuery code, define an array to store the names of all image files that are required to be displayed in the gallery:
var imgArr = ["image1.jpg", "image2.jpg", "image3.jpg", "image4.jpg", "image5.jpg", "image6.jpg"];然后初始化该数组的最小和最大索引:
var minIndex = 0; var maxIndex = imgArr.length - 1;当前索引,即当前在图库中任意时刻显示的图像的索引,初始化为
0:var currIndex = 0; -
接下来,初始化包含显示图像的文件夹的基本路径:
-
最初隐藏左右箭头。 这些将只显示在鼠标悬停在各自的热点:
$("#<%=imgPrevious.ClientID%>").hide(); $("#<%=imgNext.ClientID%>").hide(); -
Use the
.hover()method to attach themouseoverandmouseoutevent handlers on the hotspots. At runtime, theImageMapcontrol is rendered as animgelement and amapelement, as shown in the following code:<img id="imgMap" src="images/image1.jpg" usemap="#ImageMapimgMap" /> <map name="ImageMapimgMap" id="ImageMapimgMap"> <area shape="rect" coords="0,212,50,270" href="" title="Previous" alt="Previous" /> <area shape="rect" coords="630,212,680,270" href="" title="Next" alt="Next" /> </map>热点可以通过
title属性进行区分。 因此,左侧热点可以使用$("map area[title='Previous']")选择,右侧热点可以使用$("map area[title='Next']")选择。因此,可以使用
.hover()方法与左侧热点一起显示/隐藏左侧方向箭头,如下所示:$("map area[title='Previous']").hover( function () { $("#<%=imgPrevious.ClientID%>").show(); }, function () { $("#<%=imgPrevious.ClientID%>").hide(); });同样,它也可以和右边的热点一起使用来显示/隐藏右边的方向箭头,如下所示:
$("map area[title='Next']").hover( function () { $("#<%=imgNext.ClientID%>").show(); }, function () { $("#<%=imgNext.ClientID%>").hide(); });在上述代码中,当鼠标悬停时,显示所需的箭头图像,当鼠标悬停时,隐藏箭头图像。
-
我们还为热点的
click事件附加事件处理程序,如下所示: -
After clicking on the left hotspot, the previous image is displayed. In the
clickevent handler for the left hotspot, first of all, the page is prevented from posting back using the following code:evt.preventDefault();为了确保图像在循环中显示,如果显示图像是第一个图像,它的前一个图像应该是数组中的最后一个图像。 因此,更新当前索引,如下所示:
if (currIndex == minIndex) currIndex = maxIndex;对于所有其他的显示图像,当前的索引简单地通过
1递减:else currIndex--;然后使用基本路径构建映像路径:
var imgPath = basePath + imgArr[currIndex];然后图像控件的 source 属性被设置为前面的路径:
$("#<%=imgMap.ClientID%>").prop("src",imgPath); -
After clicking on the right hotspot, the next image is displayed. In the
clickevent handler for the right hotspot, first of all, the page is prevented from posting back using this code:evt.preventDefault();如果显示图像是最后一个图像,那么它的下一个图像应该是数组中的第一个图像,以确保图像在循环中显示。 因此,更新当前索引,如下所示:
if (currIndex == maxIndex) currIndex = minIndex;对于所有其他显示图像,当前索引简单地增加
1:else currIndex++;然后使用基本路径构建映像路径:
var imgPath = basePath + imgArr[currIndex];然后图像控件的 source 属性被设置为前面的路径:
$("#<%=imgMap.ClientID%>").prop("src",imgPath);这可以根据需要在循环中对图像进行正向或反向导航。
参见 also
使用 z-index 属性创建图片库
使用图像在菜单控件中创建效果
在第五章、中 ASP 的视觉效果.NET Sites,我们已经看到了 asp.net 如何 NET 菜单控件可以使用渐变和其他 CSS 效果进行动画的探索。 在本例中,让我们在 menu 控件的主菜单和子菜单项中使用图像而不是文本。 这些图像将在mouseover和mouseout事件上更新。 本例中使用的结构总结如下:
构造
|
类型
|
描述
|
| --- | --- | --- |
| $(".class") | jQuery 选择器 | 它匹配指定 CSS 类的所有元素。 |
| $("html_tag") | jQuery 选择器 | 这将选择具有指定 HTML 标记的所有元素。 |
| $(this) | jQuery 对象 | 它引用当前 jQuery 对象。 |
| .indexOf (searchString, [startIndex]) | JavaScript 函数 | 这个返回从startIndex位置开始的给定字符串中searchString第一次出现的索引(可选)。 |
| mouseout | jQuery 的事件 | 当鼠标指针离开控件时触发此操作。 它对应于 JavaScript 的mouseout事件。 |
| mouseover | jQuery 的事件 | 当鼠标指针进入控件时触发。 它对应于 JavaScript 的mouseover事件。 |
| .on() | jQuery 事件绑定 | 这将一个事件处理程序附加到一个或多个事件的匹配元素。 |
| .prop(propertyName)或.prop(propertyName, value) | jQuery 方法 | 这将为第一个匹配的元素返回指定属性的值,或者为所有匹配的元素设置指定属性的值。 |
| .replace(subString, newString) | JavaScript 函数 | 这将所有出现的subString替换为newString。 |
| .substring(startIndex, [endIndex]) | JavaScript 函数 | 它返回给定字符串的一个子字符串,从startIndex到endIndex或到字符串的末尾。 |
准备
让我们创建一个页面,使用图像在菜单控件中创建效果:
-
在这个例子中,让我们重新创建菜单,如在第五章,视觉效果在 ASP。 在动画菜单控件配方中的。NET Sites,但是这一次,使用的是图像而不是文本。 让我们从创建一个ASP 开始.NET Web 应用项目在 Visual Studio 中使用空模板,并将其命名为
Recipe6(或任何其他合适的名称)。 -
将 jQuery 库添加到项目中的
Scripts文件夹中。 -
添加一个
images文件夹,并在此文件夹中包含主菜单和子菜单项的图像。 另外,将相应菜单项的鼠标悬停图像添加到此文件夹中。 我们用来命名鼠标悬停图像的约定是*_mouseover.png。 例如,如果一个图像被命名为Home.png,那么其鼠标悬停图像将被命名为Home_mouseover.png。 -
添加一个新的 web 表单,并在表单中包含 jQuery 库。
-
通过导航到工具箱|导航部分,拖放菜单控件。
-
在表单中添加以下标记:
<div id="container"> <asp:Menu ID="Menu1" runat="server" Orientation="Horizontal"> <Items> <asp:MenuItem ImageUrl="~/images/Home.png"></asp:MenuItem> <asp:MenuItem ImageUrl="~/images/UserAccounts.png"> <asp:MenuItem ImageUrl="~/images/UserAccounts_1.png"></asp:MenuItem> <asp:MenuItem ImageUrl="~/images/UserAccounts_2.png"></asp:MenuItem> <asp:MenuItem ImageUrl="~/images/UserAccounts_3.png"></asp:MenuItem> </asp:MenuItem> <asp:MenuItem ImageUrl="~/images/Reports.png"> <asp:MenuItem ImageUrl="~/images/Reports_1.png"></asp:MenuItem> <asp:MenuItem ImageUrl="~/images/Reports_2.png"></asp:MenuItem> <asp:MenuItem ImageUrl="~/images/Reports_3.png"></asp:MenuItem> </asp:MenuItem> <asp:MenuItem ImageUrl="~/images/Settings.png"> <asp:MenuItem ImageUrl="~/images/Settings_1.png"></asp:MenuItem> <asp:MenuItem ImageUrl="~/images/Settings_2.png"></asp:MenuItem> </asp:MenuItem> </Items> </asp:Menu> </div> -
container``div区域的背景颜色使用如下样式: -
The ASP.NET engine renders the main menu items with a CSS class called
level1at runtime. Add the following styles to this class:#Menu1 .level1{ padding:0px; margin:0px; }注意事项
注意,子菜单项是用一个名为
level2的 CSS 类呈现的。 -
Now, we will use jQuery to update the main menu image on
mouseover, as shown in the following screenshot. Onmouseout, the image is restored to the original one.![Getting ready]()
同样,在任意子菜单项上的
mouseover上,相应的图像也会被更新,如下图所示:![Getting ready]()
在
mouseout上,图像恢复到原来的图像,从而在菜单项上创建所需的视觉效果。
怎么做……
将下面的代码添加到页面的<script>块中:
<script type="text/javascript">
$(document).ready(function() {
$(".level1 a img, .level2 a img").on("mouseover", function() var imageSource = $(this).prop("src");
var pos = imageSource.indexOf(".");
var strFileExt = imageSource.substring(pos, imageSource.length); imageSource = imageSource.replace(strFileExt, "_mouseover" + strFileExt); $(this).prop("src", imageSource);
}); $(".level1 a img, .level2 a img").on("mouseout", function() {
var imageSource = $(this).prop("src");
imageSource = imageSource.replace("_mouseover", "");
$(this).prop("src", imageSource);
});
});
</script>
How it works…
对 Menu 控件的影响如下:
-
在运行时,Menu 控件用
level1CSS 类呈现主菜单项,用level2CSS 类呈现子菜单项。 因此,我们为level1和level2超链接图像绑定mouseover和mouseout事件的事件处理程序,如下所示: -
The
mouseoverevent handler will display the mouseover image for that menu item. Assuming that when an image is namedimage.png, its corresponding mouseover image will beimage_mouseover.png, and we first get the image source:var imageSource = $(this).prop("src");然后,确定图像的文件扩展名:
var pos = imageSource.indexOf("."); var strFileExt = imageSource.substring(pos, imageSource.length);将原始文件扩展名替换为
_mouseover字符串,后面跟着相应的文件扩展名。 例如,如果文件扩展名是.png,那么它在图像源字符串中被_mouseover.png替换:imageSource = imageSource.replace(strFileExt, "_mouseover" + strFileExt);现在,将图像源替换为这个更新后的图像源:
$(this).prop("src", imageSource); -
When the mouse pointer moves out from the image, get the source of the image using the
.prop()method as follows:var imageSource = $(this).prop("src");将
_mouseover字符串替换为空字符串:imageSource = imageSource.replace("_mouseover", "");再次使用
prop()方法更新图像源:$(this).prop("src", imageSource);
参见 also
预览图像在 MVCrecipe 中上传
创建 5 星评级控件
5 星评级控件是一个有用的功能,当您需要评论一个项目时,比如一本书、电影、产品等等。 在本例中,让我们使用 jQuery 创建这个应用作为一个 ASP.NET 用户控件。 本例中使用的结构如下:
|构造
|
类型
|
描述
|
| --- | --- | --- |
| $("#identifier") | jQuery 选择器 | 这将根据元素的 ID 选择一个元素。 |
| $("html_tag") | jQuery 选择器 | 这将选择具有指定 HTML 标记的所有元素。 |
| $(this) | jQuery 对象 | 它引用当前 jQuery 对象。 |
| [attribute$= "value"] | jQuery 选择器 | 这将选择一个以"value"字符串结尾的指定属性的元素。 |
| click | jQuery 的事件 | 当您单击一个元素时,它就会触发。 它对应于 JavaScript 的click事件。 |
| .indexOf (searchString, [startIndex]) | JavaScript 函数 | 这将返回从startIndex位置开始的给定字符串中searchString第一次出现的索引(可选)。 |
| .length | jQuery 的财产 | 这将返回 jQuery 对象中的元素数量。 |
| .nextAll() | jQuery 方法 | 这将获得匹配元素的所有后续兄弟元素。 可以选择提供选择器。 |
| .on() | jQuery 事件绑定 | 这将一个事件处理程序附加到一个或多个事件的匹配元素。 |
| .prevAll() | jQuery 方法 | 这将获得匹配元素的所有前兄弟元素。 可以选择提供选择器。 |
| .prop(propertyName)或.prop(propertyName, value) | jQuery 方法 | 这将为第一个匹配的元素返回指定属性的值,或者为所有匹配的元素设置指定属性的值。 |
| .text() | jQuery 方法 | 这将返回每个匹配元素的组合文本内容,或者设置每个匹配元素的文本内容。 |
准备
按照以下步骤创建一个页面与 5 星级评级控制:
-
Let's create a page consisting of five star images arranged in a row. When the stars are unselected, they appear in a grey background, as shown in the following screenshot:
![Getting ready]()
在点击一个特定的星星后,所有的星星图像,直到点击的图像被选择,并出现在一个金色的背景。 例如,如果我们点击第四颗星,前四颗星就会亮起来,显示评分为 4,如下图所示:
![Getting ready]()
现在,如果你点击第一颗星星,从相反的方向开始,直到第一颗星星,所有的星星都将关闭,并显示 1 的评级,如下图所示:
![Getting ready]()
-
要创建此应用,请启动ASP.NET Web 应用项目在 Visual Studio 中使用空的模板,并将其命名为
Recipe7(或其他合适的名称)。 -
将 jQuery 库添加到项目中的
Scripts文件夹中。 -
在项目中添加一个
images文件夹。 在这个文件夹中包含两种类型的图像,即一个灰色背景的星形图像和一个金色背景的星形图像。 -
添加一个 web 表单到项目中,并在表单中包含 jQuery 库。
-
Since we want to create the 5-star rating system as a standalone control, add a
Controlsfolder to the project. Now, right-click on this folder in the Solution Explorer tab and go to Add | New Item. From the dialog box that is launched, select Web Forms User Control and name the controlRatingControl.acsx, as shown in the following screenshot. Click on the Add button.![Getting ready]()
-
在Source模式下打开 control
RatingControl。 转到工具箱|Standard,在用户控件上拖放一个Panel控件。 在Panel控件中拖放五个Image控件。 另外,在Panel控件下面添加两个Label控件来显示当前的评级。 这将在用户控件中创建以下标记: -
通过向
system.web节点中的web.config文件添加以下代码来注册用户控件:<pages> <controls> <add tagPrefix="uc1" tagName="RatingControl" src="~/Controls/RatingControl.ascx"/> </controls> </pages> -
Now, open the web form in the Design or Source mode, and drag and drop the RatingControl control on the form area. This will add the following markup to the web form:
<uc1:RatingControl runat="server" id="RatingControl" />另外,请注意下面的
@Register指令被添加到页面中:<%@ Register Src="~/Controls/RatingControl.ascx" TagPrefix="uc1" TagName="RatingControl" %>
怎么做……
在用户控件的@Control指令后添加以下 jQuery 代码到<script>块:
<script type="text/javascript">
$(document).ready(function() {
var BasePath = "images/";
var greyImg = "star_grey.png";
var goldImg = "star_golden.png";
$("#<%=pnlImgContainer.ClientID%> img").on("click",
function() {
if ($(this).prop("src").indexOf(greyImg) > -1) {
$(this).prop("src", BasePath + goldImg);
$(this).prevAll("img").prop("src", BasePath + goldImg);
} else {
$(this).prop("src", BasePath + greyImg);
$(this).nextAll("img").prop("src", BasePath + greyImg);
}
var rating = $("# <%=pnlImgContainer.ClientID%> img[src$='" + goldImg + "']").length;
$("#<%=lblStarRating.ClientID%>").text(rating);
});
});
</script>
How it works…
5 星级评级控制设计如下:
-
在 jQuery 代码中,设置图像的基本路径以及开启(金色背景)和关闭(灰色背景)图像的各自图像名称:
var BasePath = "images/"; var greyImg = "star_grey.png"; var goldImg = "star_golden.png"; -
将一个点击事件处理程序附加到容器面板中的每个图像上,如下所示:
-
在前面的处理程序中,判断点击的图像是否为灰色背景图像,如下:
if ($(this).prop("src").indexOf(greyImg) > -1) -
If the preceding condition is
true, then update the clicked image to display the golden background image, as follows:$(this).prop("src", BasePath + goldImg);同时,将前面所有的图片也修改为金色背景图片:
$(this).prevAll("img").prop("src", BasePath + goldImg); -
If the condition in step 3 is
false, update the clicked image to display the grey background image, as follows:$(this).prop("src", BasePath + greyImg);同时,将后面的所有图像也更改为灰色背景图像:
$(this).nextAll("img").prop("src", BasePath + greyImg); -
Determine the rating by counting the number of golden stars using the source property of each Image control:
var rating = $("# <%=pnlImgContainer.ClientID%> img[src$='" + goldImg + "']").length;在页面上的 Label 控件中显示此评级:
$("#<%=lblStarRating.ClientID%>").text(rating);
还有更多的…
由于评级控件是作为一个独立的用户控件实现的,所以它的多个实例可以添加到 web 表单中。 因此,在窗体上拖放另一个实例,这样页面上就有两个这样的控件:
<uc1:RatingControl runat="server" id="RatingControl" />
<uc1:RatingControl runat="server" id="RatingControl2" />
该页面现在将显示两个独立的控件,如下面的截图所示。 每个控件都可以独立使用。

参见 also
预览图像在 MVCrecipe 中上传
在 MVC 中预览图像上传
在这个示例中,让我们创建一个 MVC 应用,它可以在将图像上传到服务器之前使用客户端脚本预览图像。 注意,此菜谱仅覆盖客户机脚本,并没有处理用于上传的服务器代码。 下表显示了本例中使用的构造的快速摘要:
|构造
|
类型
|
描述
|
| --- | --- | --- |
| $("#identifier") | jQuery 选择器 | 这将根据元素的 ID 选择一个元素。 |
| 或.attr("name", "value") | jQuery 方法 | 这将返回一个具有匹配元素所需属性值的字符串。 它还可以用于将属性设置为所需的值。 |
| change | jQuery 的事件 | 当元素的值发生变化时,将触发。 它对应于 JavaScript 的change事件。 |
| FileReader.onloadend | FileReader 接口提供的事件处理程序 | 此定义了loadend事件的事件处理程序。 它在每次事件完成时执行。 |
| FileReader.readAsDataUrl() | FileReader 接口提供的方法 | 它读取文件或 blob(不可变原始数据的类文件对象)的内容。 读取完成后,result 属性返回已读取文件数据的 URL。 |
| FileUpload.files | 文件列表对象 | 从 file upload 元素中选择的文件作为FileList对象返回。 |
| FileUpload.files.length | FileList 对象的属性 | 这是FileList对象中的文件数。 |
| FileUpload.file.type | FileList 对象的属性 | 这将返回给定文件对象的文件类型。 |
| .match(regexp) | JavaScript 函数 | 它将字符串与正则表达式相匹配。 |
| .on() | jQuery 事件绑定 | 这将一个或多个事件的事件处理程序附加到匹配的元素。 |
| window.File | 文件 API 提供的接口 | 这提供了文件的信息属性,例如名称、最后修改日期等等。 |
| window.FileReader | 文件 API 提供的接口 | 这允许读取文件或 blob(不可变原始数据的类文件对象)的内容。 |
准备
按照以下步骤构建一个图像预览的 MVC 应用:
-
Let's create an MVC application with an image preview area and file upload control, as shown in the following screenshot:
![Getting ready]()
-
On browsing and selecting an image file, a preview of the image can be seen in the shaded area on the page, as shown in the following screenshot:
![Getting ready]()
-
To create the preceding page, launch a new ASP.NET Web Application project in Visual Studio. Select the Empty template and ensure that the MVC checkbox is selected, as shown in the following screenshot. Name the application
Recipe8(or any other suitable name).![Getting ready]()
-
ASP.NET 自动使用 jQuery 库文件将
Scripts文件夹添加到 MVC 项目中。 您可以保留这些文件,也可以将它们替换为最新版本。 -
Right-click on the Controllers folder in the project and go to Add | Controller. From the dialog box that opens up, select MVC5 Controller – Empty, and then click on the Add button, as shown in the following screenshot:
![Getting ready]()
-
控制器名称控制器名称
DefaultController。 默认情况下,Visual Studio 将Index ActionResult添加到控制器。 -
In the Solution Explorer tab, right-click by navigating to Views | Default and go to Add | View. Enter
Indexfor the View name, and click on the Add button on the Add View dialog box, as shown in the following screenshot. Note that the Template selected is Empty (without model):![Getting ready]()
-
添加一个图像元素和一个文件上传元素到视图。 此外,还包括 jQuery 库。 因此,视图的标记如下:
<h2>Preview a file using upload control</h2> <script src="~/Scripts/jquery-2.1.4.js"></script> <div> <img id="imgPreview" alt="Preview your image here" width="400" height="300" /><br/><br/> <input type="file" id="FileUpload1" /> </div> -
通过添加以下样式,为前面的图像元素包含背景色:
怎么做……
将以下 jQuery 代码添加到视图的<script>块中:
<script type="text/javascript">
$(document).ready(function() {
$("#FileUpload1").on("change", function() {
if (this.files.length == 0) {
alert("No image is selected");
return;
}
if (!window.File || !window.FileReader) {
alert("File API is not supported in this browser");
return;
}
if (this.files[0].type.match("image.*")) {
var reader = new FileReader();
reader.readAsDataURL(this.files[0]);
reader.onloadend = function() {
$("#imgPreview").attr("src", this.result);
}
}
});
});
</script>
How it works…
图像预览工作如下:
-
要运行应用,在解决方案资源管理器选项卡中,右键单击视图|Default|索引。 cshtml,点击在浏览器中查看。 在浏览器中成功加载页面后,浏览需要上传的图像文件。 该页面将在预览区显示图像。
-
This is accomplished by attaching an event hander for the
changeevent of the file upload control, as follows:$("#FileUpload1").on("change", function () {…});每次在文件上传控件中浏览和选择文件时触发此事件。
-
在前面的处理程序中,首先,我们检查文件上传控件是否返回一个空对象,如下所示:
-
其次,我们还需要验证浏览器是否支持
File API。 这可以通过以下检查来完成:if (!window.File || !window.FileReader) { alert("File API is not supported in this browser"); return; } -
Next, check whether the selected file is an image or not using a regular expression on the file type:
if (this.files[0].type.match("image.*"))注意事项
由于 file upload 元素返回一个
FileList对象,我们可以使用index 0选择第一个文件,即files[0]。 然后匹配文件类型上的正则表达式image.*,只过滤图像文件。如果选择的文件是映像文件,则创建一个
FileReader对象来读取该文件:var reader = new FileReader();现在,使用
FileReader对象,读取文件的内容:reader.readAsDataURL(this.files[0]);为
loadend事件编写事件处理程序。 这将在文件被完全读取后执行:reader.onloadend = function () {…}在前面的事件处理程序中,由于 result 属性包含文件数据的 URL,我们可以将图像元素的源属性设置为该 URL,如下所示:
$("#imgPreview").attr("src", this.result);
参见 also
使用图像在菜单控件配方中创建效果
七、使用 jQuery Ajax
本章演示如何使用 jQuery 通过 Ajax 发布异步请求。 所涵盖的食谱清单如下:
- 用 ASP 建立 Ajax。 使用 jQuery 净
- 使用页面的方法
- 消费 Web 服务
- 使用 WCF 服务
- 从 Web API 检索数据
- 对控制器操作进行 Ajax 调用
- 对 HTTP 处理程序进行 Ajax 调用
简介
AJAX(异步 JavaScript 和 XML)是 Adaptive Path 的 Jesse James Garrett 创造的一个术语。 它代表不同技术的组合,帮助您与服务器无缝通信,而不需要刷新页面。 Ajax 应用涉及以下技术:
- 用于运行核心 Ajax 引擎的 JavaScript
- 对象来与服务器通信
- 使用 HTML 和 CSS 或 XSLT 的 web 演示
- DOM 来处理 HTML 结构
- 用于数据交换的 XML 和 JSON
XmlHttpRequest对象用于向服务器发送 HTTP/HTTPS 请求。 大多数现代浏览器都有一个内置的XmlHttpRequest对象。
注意事项
JSON(JavaScript 对象表示法)是一种轻量级的数据交换格式,越来越多地用于 Ajax 应用。 它基本上是一个名称/值对的集合,可以用于不同的数据类型,如字符串、数字、布尔值、数组和对象。
在一个典型的 web 应用中,客户端将数据提交给服务器进行处理,服务器将刷新后的内容返回给客户端。 这将导致可见的页面刷新,并且用户需要等待页面重新加载后才能与页面进行进一步的交互。 这个请求/响应流程如下图所示:

Ajax 为浏览器和服务器之间的通信提供了一种新的范例。 使用 Ajax,可以更新网页的部分内容,而无需将整个页面发送到服务器。 通过在幕后进行通信,无需显式页面刷新。 用户可以继续使用网页,而不必等待服务器的响应,如下图所示:

在基于 Ajax 的应用中,对 Ajax 引擎进行 JavaScript 调用,该引擎使用XmlHttpRequest对象将请求异步发送到服务器。 因此,后端通信变得透明,并且用户与应用的交互不会中断。 这增强了页面的交互性; 从而改善用户的体验。 同时,提高了页面的性能和速度。
jQuery 库提供了许多使用 Ajax 的方法。 在本章中,我们将探讨使用以下方法:
$.ajaxSetup(options):此方法可用于定义在页面上进行 Ajax 调用的默认设置。 设置一次完成,页面上的所有后续 Ajax 调用都使用这些默认设置。$.ajax(settings):这是一个通用的低级函数,可以帮助您创建任何类型的 Ajax 请求。 有很多配置设置,可以使用这个函数应用如 HTTP 请求的类型(GET/POST/PUT/DELETE),请求 URL,参数被发送到服务器,数据类型的响应,以及要执行的回调函数的成功/失败的调用 Ajax 调用。$("…").load():这是一个快捷方法,用于从服务器加载文本或 HTML 内容,并将其显示在匹配的元素中。$.getJSON():该方法向服务器发送 HTTPGET请求。 数据以 JSON 格式返回。
注意事项
从服务器接收到的响应的数据类型可以是文本、HTML、XML、JSON 或 JSONP。 在底层,快捷方法使用$.ajax()方法向服务器发送请求。
用 ASP 建立 Ajax。 使用 jQuery 净
这个配方演示了如何使用$.ajaxSetup()函数来配置全局设置,以便在 web 页面上进行 Ajax 调用。 这些设置将在多个 Ajax 调用中使用。 下表总结了本例中使用的结构:
构造
|
类型
|
描述
|
| --- | --- | --- |
| $("#identifier") | jQuery 选择器 | 这将根据元素的 ID 选择一个元素 |
| $.ajax() | jQuery 函数 | 这将向服务器发送一个带有设置选项的 Ajax 请求。 |
| $.ajaxSetup() | jQuery 函数 | 这将为 Ajax 请求设置默认值。 |
| .append() | jQuery 方法 | 这将在每个匹配元素的末尾插入内容。 |
| click | jQuery 的事件 | 当您单击一个元素时,它就会触发。 它对应于 JavaScript 的click事件。 |
| .each() | jQuery 方法 | 这将遍历匹配的元素,并为每个元素执行一个函数。 |
| event.preventDefault() | jQuery 方法 | 这将防止触发事件的默认动作。 |
| .find() | jQuery 方法 | 这将查找与筛选器匹配的所有元素。 |
| .html() | jQuery 方法 | 这将返回第一个匹配元素的 HTML 内容,或者设置每个匹配元素的 HTML 内容。 |
| .load() | jQuery 方法 | 这会从服务器加载文本或 HTML 数据,并将其显示在匹配的元素中。 |
| .on() | jQuery 事件绑定 | 这将一个或多个事件的事件处理程序附加到匹配的元素。 |
| .text() | jQuery 方法 | 这会返回每个匹配元素的的组合文本内容,或者设置每个匹配元素的文本内容。 |
准备
按照下面的步骤来使用 ASP 设置 Ajax.NET 使用 jQuery:
-
Let's create a web page that triggers Ajax calls to retrieve the HTML and XML data, respectively. On loading, the page will display a
Buttoncontrol, as shown in the following screenshot:![Getting ready]()
点击
Button控件后,页面将从各个来源检索内容,并以以下格式显示在页面上:![Getting ready]()
-
为了创建此页面,启动一个ASP.NET Web 应用项目在 Visual Studio 中使用空模板,并将其命名为
Recipe1(或其他合适的名称)。 -
将 jQuery 库添加到项目中
Scripts文件夹中。 -
添加一个 web 表单到项目中,并在表单中包含 jQuery 库。
-
接下来,我们将创建一个包含一些测试数据的 HTML 文件。 要做到这一点,右键单击Solution Explorer选项卡中的项目,然后转到Add|New Item。 从对话框中的Installed templates部分,转到Web|HTML Page。 将该文件命名为
Sample.html。 添加以下内容到这个 HTML 文件: -
通过在Solution Explorer选项卡中右键单击项目,并导航到Add|New Item,将一个 XML 文件添加到项目。 在弹出的对话框中,从“Installed templates”中选择“Data|XML File”。 将文件命名为
Sample.xml,文件中包含以下内容:<?xml version="1.0" encoding="utf-8" ?> <BookShelf> <Book> <Title>Huckleberry Finn</Title> <Author>Mark Twain</Author> <Category>Classic</Category> </Book> <Book> <Title>David Copperfield</Title> <Author>Charles Dickens</Author> <Category>Classic</Category> </Book> <Book> <Title>The Alchemist</Title> <Author>Paulo Coelho</Author> <Category>Fiction</Category> </Book> <Book> <Title>You Can Win</Title> <Author>Shiv Khera</Author> <Category>Non-Fiction</Category> </Book> </BookShelf> -
向表单添加一个
Button控件以及两个空的div元素:一个用于显示 HTML 内容,另一个用于显示 XML 内容。 因此,表单的标记如下:<asp:Button ID="btnLoad" runat="server" Text="Click to load content using AJAX" /> <div id="htmlcontent"> </div> <div id="xmlcontent"> </div> -
要样式化从 HTML 和 XML 文件中检索的内容,请向
head元素添加以下样式:
怎么做……
在页面的script块中包含以下 jQuery 代码:
script type="text/javascript">
$(document).ready(function() {
$.ajaxSetup({
method: "GET",
data: {},
timeout: 2000,
cache: false
});
$("#<%=btnLoad.ClientID%>").on("click", function(evt) {
evt.preventDefault();
$.ajax({
url: "Sample.html",
dataType: "html",
success: function(response) {
$("#htmlcontent").html("").append(response);
},
error: function(jqXHR, textStatus, errorThrown) {
if (textStatus == "error") {
alert("An error has occurred: " + jqXHR.status + " " + jqXHR.statusText);
}
}
});
$.ajax({
url: "Sample.xml",
dataType: "xml",
success: function(response) {
$("#xmlcontent").html("").append("<h3>Book Shelf from XML</h3>");
$("#xmlcontent").append("<table>");
$("#xmlcontent table").append("<tr><th>Title</th><th>Author</th><th>Category</th></tr>");
$(response).find("Book").each(function() {
$("#xmlcontent table").append("<tr><td>" + $(this).find("Title").text() + "</td><td>" + $(this).find("Author").text() + "</td><td>" + $(this).find("Category").text() + "</td></tr>");
});
},
error: function(jqXHR, textStatus, errorThrown) {
if (textStatus == "error") {
alert("An error has occurred: " + jqXHR.status + " " + jqXHR.statusText);
}
}
});
});
});
</script>
How it works…
使用 Ajax 检索 HTML 和 XML 内容的步骤如下:
-
When the page is launched, the
$.ajaxSetup()function configures the global settings for all Ajax calls on the page:$.ajaxSetup({ method: "GET", data: {}, timeout: 2000, cache: false });它设置以下属性:
- 请求的类型/方法设置为 HTTP
GET - 空数据被发送到服务器
- 设置了一个
2000毫秒的超时,以便如果服务器在此时间范围内没有响应,可以终止调用 - 缓存被设置为
false,因此浏览器不会缓存请求的内容
- 请求的类型/方法设置为 HTTP
-
When you click on the button on the page, its corresponding
clickevent handler is triggered:$("#<%=btnLoad.ClientID%>").on("click", function (evt) {…});在此事件处理程序中,首先,由于按钮
click事件,阻止页面返回:evt.preventDefault();接下来,通过设置必要的选项来启动对
Sample.html页面的 Ajax 调用:$.ajax({ url: "Sample.html", dataType: "html", success: function (response) { $("#htmlcontent").html("").append(response); }, error: function (jqXHR, textStatus, errorThrown) { if (textStatus == "error") { alert("An error has occurred: " + jqXHR.status + " " + jqXHR.statusText); } } });前面的代码片段在对 HTML 页面进行 Ajax 调用时设置了以下选项:
- 请求 URL 设置为
Sample.html。 - 服务器的预期响应的数据类型设置为
html。 - 当向服务器发出的请求成功时,定义一个回调函数。 该功能清除 ID 为
htmlcontent的div区域的内容,并显示从相同 ID 的服务器接收的数据。 - 当向服务器发出的请求失败时,定义一个回调函数。 这个回调函数有三个参数:
jqXHR(XMLHttpRequest对象),textStatus(类型的错误,如abort、parsererror,timeout,error或null),和【显示】(一个可选的异常对象)。 当textStatus参数为error时,我们显示jqXHR``XMLHttpRequest对象中的status和statusText值。
- 请求 URL 设置为
-
Next, initiate another Ajax call to the
Sample.xmlfile with the required options:$.ajax({ url: "Sample.xml", dataType: "xml", success: function(response) { $("#xmlcontent").html("").append("<h3>Book Shelf from XML</h3>"); $("#xmlcontent").append("<table>"); $("#xmlcontent table").append("<tr><th>Title</th><th>Author</th><th>Category</th></tr>"); $(response).find("Book").each(function() { $("#xmlcontent table").append("<tr><td>" + $(this).find("Title").text() + "</td><td>" + $(this).find("Author").text() + "</td><td>" + $(this).find("Category").text() + "</td></tr>"); }); }, error: function(jqXHR, textStatus, errorThrown) { if (textStatus == "error") { alert("An error has occurred: " + jqXHR.status + " " + jqXHR.statusText); } } });在上述请求中设置了以下选项:
-
请求 URL 为
Sample.xml。 -
服务器响应的预期数据类型为
xml。 -
当向服务器发出的请求成功时,定义一个回调函数。 这个回调函数清除带有
xmlcontentID 的div元素,并添加一个头部,如下面的代码片段所示: -
然后在这个
div元素中添加一个空的表元素,并添加table标题:$("#xmlcontent").append("<table>"); $("#xmlcontent table").append("<tr><th>Title</th><th>Author</th><th>Category</th></tr>"); -
对于 XML 文件中的每个
Book节点,它显示相应的子节点:Title、Author和Category,如下所示: -
当向服务器发出的请求不成功时,定义一个回调函数。 这个回调函数有三个参数:
jqXHR(XMLHttpRequest对象),textStatus(类型的错误,如abort、parsererror,timeout,error或null),和【显示】(一个可选的异常对象)。 当textStatus参数值为error时,我们显示XMLHttpRequest对象中的status和statusText值。
-
还有更多的…
为了使用GET请求异步检索文本或 HTML 内容,jQuery 提供了一个.load()快捷方式。 使用这个函数,我们可以选择对Sample.html文件进行第一次 Ajax 调用,如下所示:
$("#htmlcontent").html("").load("Sample.html",
function (response, status, xhr) {
if (status == "error") {
alert("An error has occurred: " + xhr.status + " " + xhr.statusText);
}
});
注意在这个函数中指定了一个回调函数。 这将在.load()方法完成时执行。 回调函数具有参数,如response(如果调用成功,其中包含结果内容)、status(其中包含调用的状态)和xhr(XMLHttpRequest对象)。
参见 also
消费页面方法配方
消耗页面方法
Page 方法提供了一种从客户端脚本调用服务器端代码的方便方法。 它们只是使用System.Web.Services.WebMethod标签装饰的服务器端方法。 在本菜谱中,我们将在页面方法中使用 Northwind 数据库来检索来自特定国家的客户列表。 该方法将使用 jQuery Ajax 从客户机脚本调用。
下表总结了本例中使用的结构:
|构造
|
类型
|
描述
|
| --- | --- | --- |
| $("#identifier") | jQuery 选择器 | 这将根据元素的 ID 选择一个元素。 |
| $("html_tag") | jQuery 选择器 | 这将选择具有指定 HTML 标记的所有元素。 |
| $.ajax() | jQuery 函数 | 这将向服务器发送一个带有设置选项的 Ajax 请求。 |
| .append() | jQuery 方法 | 这将在每个匹配元素的末尾插入内容。 |
| click | jQuery 的事件 | 当您单击一个元素时,将触发此操作。 它对应于 JavaScript 的click事件。 |
| event. preventDefault() | jQuery 方法 | 这将防止触发事件的默认动作。 |
| :gt(i) | jQuery 选择器 | 这将选择索引大于i的匹配元素。 它使用一个从零开始的索引。 |
| .hide() | jQuery 方法 | 这将隐藏匹配的元素。 |
| :hidden | jQuery 选择器 | 这将选择隐藏元素。 |
| .is() | jQuery 方法 | 如果匹配的元素满足给定条件,则返回一个布尔值。 |
| .on() | jQuery 事件绑定 | 这将一个或多个事件的事件处理程序附加到匹配的元素。 |
| .remove() | jQuery 方法 | 这会从 DOM 中删除匹配的元素。 |
| .show() | jQuery 方法 | 这会显示匹配的元素。 |
| .trim() | JavaScript 函数 | 这将删除字符串开头和结尾的空白。 |
| .val() | jQuery 方法 | 返回第一个匹配元素的值,或者设置每个匹配元素的值。 |
| window.location.href | JavaScript 的财产 | 这将返回当前页面的 URL。 |
准备
遵循以下步骤来构建一个公开页面方法的网页:
-
Let's create a web page with a
DropDownListcontrol consisting of a list of countries, as shown in the following screenshot:![Getting ready]()
下拉菜单选择任意国家后,页面显示所选国家过滤的客户列表,如下图所示:
![Getting ready]()
-
要创建此应用,请启动ASP.NET Web 应用项目在 Visual Studio 中使用空模板,并将其命名为
Recipe2(或任何其他合适的名称)。 -
将 jQuery 库添加到项目的
Scripts文件夹中。 -
添加一个 web 表单到项目中,并在表单中包含 jQuery 库。
-
In the Solution Explorer tab, right-click on the project and go to Add | New Item. From the launched dialog box, select Data under the Installed templates section on the left-hand panel. Select ADO.NET Entity Data Model from the middle panel. Enter a suitable name for the model such as
Northwind, and click on the Add button:![Getting ready]()
-
This will launch the Entity Data Model Wizard dialog box, as shown in the following screenshot. Select EF Designer from database and click on the Next button:
![Getting ready]()
在下一个窗口中,添加到 Northwind 数据库的新连接。 将此连接保存在
web.config中为NorthwindEntities,然后点击Next:![Getting ready]()
接下来,从表对象列表中检查
Customers表,并点击Finish按钮:![Getting ready]()
-
In the code-behind file of the web form, that is,
Default.aspx.vb(VB) orDefault.aspx.cs(C#), add the following page method.对于 VB,代码如下:
<System.Web.Services.WebMethod> Public Shared Function GetCustomers(ByVal sCountry As String) As Customer() Dim CustomerList As List(Of Customer) = New List(Of Customer)() Dim db As NorthwindEntities = New NorthwindEntities() Dim Query = From cust In db.Customers Where cust.Country = sCountry Select cust For Each custObj In Query Dim CustomerRecord As Customer = New Customer() CustomerRecord.CustomerID = custObj.CustomerID CustomerRecord.CompanyName = custObj.CompanyName CustomerRecord.ContactName = custObj.ContactName CustomerRecord.ContactTitle = custObj.ContactTitle CustomerRecord.City = custObj.City CustomerList.Add(CustomerRecord) Next Return CustomerList.ToArray End Function对于 c#,代码如下:
[System.Web.Services.WebMethod] public static Customer[] GetCustomers(string sCountry) { List<Customer> CustomerList = new List<Customer>(); NorthwindEntities db = new NorthwindEntities(); var query = from cust in db.Customers where cust.Country == sCountry select cust; foreach (var custObj in query) { Customer CustomerRecord = new Customer(); CustomerRecord.CustomerID = custObj.CustomerID; CustomerRecord.CompanyName = custObj.CompanyName; CustomerRecord.ContactName = custObj.ContactName; CustomerRecord.ContactTitle = custObj.ContactTitle; CustomerRecord.City = custObj.City; CustomerList.Add(CustomerRecord); } return CustomerList.ToArray(); } -
The preceding
GetCustomers()page method receives thecountryfield as an input parameter. It filters customer records bycountryand returns an array of theCustomertype.注意事项
注意,页面方法需要有以下配置:
- 该方法应装饰有
System.Web.Services.WebMethod标签。 - 它应该声明为共享(VB)或静态(c#)。
- 它以
sCountry作为输入参数。 这个参数应该由客户机脚本通过 Ajax 调用发送。
- 该方法应装饰有
-
向 web 表单添加一个框架表元素,以显示检索到的客户列表。 因此,表单的标记如下:
<asp:Label ID="lblSelectCountry" runat="server" Text="Please select the country to view customers:"></asp:Label><br /><br /> <asp:DropDownList ID="ddlSelectCountry" runat="server"> <asp:ListItem Text="--Select Country--" Value=""></asp:ListItem> <asp:ListItem Text="Argentina" Value="Argentina"></asp:ListItem> <asp:ListItem Text="Brazil" Value="Brazil"></asp:ListItem> <asp:ListItem Text="Canada" Value="Canada"></asp:ListItem> <asp:ListItem Text="Italy" Value="Italy"></asp:ListItem> <asp:ListItem Text="Mexico" Value="Mexico"></asp:ListItem> <asp:ListItem Text="UK" Value="UK"></asp:ListItem> <asp:ListItem Text="USA" Value="USA"></asp:ListItem> </asp:DropDownList> <asp:Button ID="btnRetrieve" runat="server" Text="Retrieve" /> <br /><br /> <table id="tblResponse"> <thead> <tr> <th>Customer ID</th> <th>Company Name</th> <th>Contact Name</th> <th>Contact Title</th> <th>City</th> </tr> </thead> </table> -
在页面上的
head元素中添加以下样式:
怎么做……
在<script>块中包含以下 jQuery 代码:
<script type="text/javascript">
$(document).ready(function() {
$("#tblResponse").hide();
$("#<%=btnRetrieve.ClientID%>").on("click", function(evt) {
evt.preventDefault();
var sCountry = $("#<%=ddlSelectCountry.ClientID%>").val().trim();
if (sCountry != "") {
var loc = window.location.href;
$.ajax({
url: loc + "/GetCustomers",
method: "POST",
data: '{ "sCountry": "' + sCountry + '"}',
dataType: "json",
contentType: "application/json; charset=utf-8",
timeout: 5000,
cache: false,
success: function(response) {
$("#tblResponse tr:gt(0)").remove();
if ($("#tblResponse").is(":hidden"))
$("#tblResponse").show();
$.each(response.d,
function() {
$("#tblResponse").append("<tr><td>" + this['CustomerID'] + "</td><td>" + this['CompanyName'] + "</td><td>" + this['ContactName'] + "</td><td>" + this['ContactTitle'] + "</td><td>" + this['City'] + "</td></tr>");
});
},
error: function(jqXHR, textStatus, errorThrown) {
if (textStatus == "error") {
alert("An error has occurred: " + jqXHR.status + " " + jqXHR.statusText);
}
}
});
} else
alert("Please select a country to display the customer list.");
});
});
</script>
How it works…
发布对页面方法的 Ajax 调用如下:
-
当页面启动时,用于显示客户列表的
table元素最初是隐藏的:$("#tblResponse").hide(); -
An event handler is defined for the
clickfunction of the button in the form:$("#<%=btnRetrieve.ClientID%>").on("click", function (evt) {…});在此事件处理程序中,使用以下代码阻止页面返回:
evt.preventDefault();从
DropDownList控件中选取的值,即选取的国家:var sCountry = $("#<%=ddlSelectCountry.ClientID%>").val().trim();前面的字符串被调整以删除空白(如果有的话)。 如果所选国家非空,使用
window.location.hrefJavaScript 属性找到当前页面的 URL:var loc = window.location.href;现在,对页面方法进行 Ajax 调用:
$.ajax({ url: loc + "/GetCustomers", method: "POST", data: '{ "sCountry": "' + sCountry + '"}', dataType: "json", contentType: "application/json; charset=utf-8", timeout: 5000, cache: false, success: function (response) $("#tblResponse tr:gt(0)").remove(); if ($("#tblResponse").is(":hidden")) $("#tblResponse").show(); $.each(response.d, function () { $("#tblResponse").append("<tr><td>" + this['CustomerID'] + "</td><td>" + this['CompanyName'] + "</td><td>" + this['ContactName'] + "</td><td>" + this['ContactTitle'] + "</td><td>" + this['City'] + "</td></tr>"); }); }, error: function (jqXHR, textStatus, errorThrown) { if (textStatus == "error") { alert("An error has occurred: " + jqXHR.status + " " + jqXHR.statusText); } } });在上述通话中,设置了以下选项:
-
请求 URL 被设置为页面方法,可以通过
UrlOfCurrentPage/NameOfPageMethod访问。 -
请求的类型/方法被设置为
POST,因为我们正在向服务器发送表单数据。 -
The data, that is, the selected country is sent to the server as a JSON formatted string. Remember that the page method has an input parameter,
sCountry. This is sent as a name/value pair as follows:data: '{ "sCountry": "' + sCountry + '"}',注意事项
需要注意的是,前面 JSON 字符串中的
sCountry名称是页面方法的输入参数。 -
服务器响应的数据类型为
json。 -
发送的请求内容类型设置为
application/json,字符设置为UTF-8。 -
指定了一个
5000毫秒的超时时间,在此时间之后,如果服务器没有响应,请求将被终止。 -
缓存被设置为
false,因此浏览器不会缓存内容。 -
当请求成功时定义一个回调函数。 在这个函数中,显示表的内容被清空,删除除了表头以外的所有行:
$("#tblResponse tr:gt(0)").remove(); -
如果显示表被隐藏,则显示给用户:
if ($("#tblResponse").is(":hidden")) $("#tblResponse").show(); -
然后,我们循环遍历返回的响应中的每个元素,检索
CustomerID、CompanyName、ContactName、ContactTitle和City字段,如下所示:
注意事项
注意,为了访问从服务器返回的数据,我们在前面的代码中使用了
response.d。 -
-
当请求不成功时,定义一个回调函数。 如果
textStatus参数为error,则显示XmlHttpRequest对象的status和statusText值。 -
用户也可能不从
DropDownList控件中选择任何国家。 因此,当所选字段为空时,程序应该显示一条消息:alert("Please select a country to display the customer list.");
参见 also
对 HTTP 处理程序配方进行 AJAX 调用
使用 Web 服务
jQuery Ajax 允许您通过客户端代码使用 web 服务。 在这个食谱中,我们将表单数据发送到 web 服务方法。 本例中使用的结构总结如下表:
|构造
|
类型
|
描述
|
| --- | --- | --- |
| $("#identifier") | jQuery 选择器 | 这将根据元素的 ID 选择一个元素。 |
| $("html_tag") | jQuery 选择器 | 这将选择具有指定 HTML 标记的所有元素。 |
| $.ajax() | jQuery 函数 | 这将向服务器发送一个带有设置选项的 Ajax 请求。 |
| .append() | jQuery 方法 | 这将在每个匹配元素的末尾插入内容。 |
| click | jQuery 的事件 | 当您单击一个元素时,它就会触发。 它对应于 JavaScript 的click事件。 |
| event. preventDefault() | jQuery 方法 | 这将防止触发事件的默认动作。 |
| .focus() | jQuery 事件绑定 | 这将触发元素的focus事件或将事件处理程序绑定到focus事件。 |
| :gt(i) | jQuery 选择器 | 这将选择索引大于i的匹配元素。 它使用了从零开始的索引。 |
| :hidden | jQuery 选择器 | 这将选择隐藏元素。 |
| .hide() | jQuery 方法 | 这将隐藏匹配的元素。 |
| .is() | jQuery 方法 | 如果匹配的元素满足给定条件,则返回一个布尔值。 |
| .on() | jQuery 事件绑定 | 这将一个或多个事件的事件处理程序附加到匹配的元素。 |
| .remove() | jQuery 方法 | 这会从 DOM 中删除匹配的元素。 |
| .show() | jQuery 方法 | 这会显示匹配的元素。 |
| .text() | jQuery 方法 | 这将返回每个匹配元素的组合文本内容,或者设置每个匹配元素的文本内容。 |
| .trim() | JavaScript 函数 | 这将删除字符串开头和结尾的空白。 |
| .val() | jQuery 方法 | 返回第一个匹配元素的值,或者设置每个匹配元素的值。 |
准备
遵循以下步骤构建一个将使用 web 服务的 web 页面:
-
In this recipe, let's create a form where the user can search for employee records by the first name or last name, as shown in the following screenshot:
![Getting ready]()
输入需要搜索的关键字,如果匹配,则显示搜索结果,如下图所示:
![Getting ready]()
如果没有找到匹配的,页面只显示一条消息,如下图所示:
![Getting ready]()
-
要创建此应用,请启动ASP.NET Web 应用项目在 Visual Studio 中使用空模板,并将其命名为
Recipe3(或任何其他合适的名称)。 -
将 jQuery 库添加到项目中
Scripts文件夹中。 -
添加一个 web 表单到项目中,并在表单中包含 jQuery 库。
-
Include the following markup in the form:
<h3>Key in the Employee name to search:</h3> <asp:TextBox ID="txtKeyword" runat="server"></asp:TextBox> <asp:Button ID="btnSearch" runat="server" Text="Search" /> <br /><br /> <table id="tblResponse"> <thead> <tr> <th>Employee ID</th> <th>First Name</th> <th>Last Name</th> <th>City</th> <th>Country</th> <th>Home Phone</th> </tr> </thead> </table> <br /> <asp:Label ID="lblMessage" runat="server"></asp:Label>注意,表单有一个
Label控件lblMessage。 该字段将用于向用户显示信息/错误消息(如果有的话)。 -
使用下面的 CSS 样式来设置页面元素:
-
Add an
Employeeclass to the project by right-clicking on the project and navigating to Add | Class. Name the classEmployee.vb(VB) orEmployee.cs(C#). Add the following properties to the class.对于 VB,代码如下:
Public Class Employee Public Property EmployeeID As String Public Property LastName As String Public Property FirstName As String Public Property City As String Public Property Country As String Public Property HomePhone As String End Class对于 c#,代码如下:
public class Employee { public String EmployeeID { get; set; } public String LastName { get; set; } public String FirstName { get; set; } public String City{ get; set; } public String Country { get; set; } public String HomePhone { get; set; } } -
现在,在Solution Explorer选项卡中右键单击项目,然后转到Add|New Folder。 将新文件夹命名为
Services。 -
Right-click on the
Servicesfolder and go to Add | New Item. From the launched dialog box, select Web from the Installed templates on the left-hand side of the screen. From the middle panel, select Web Service (ASMX). Give the service a suitable name, such asNorthwindService.asmx, and click on the Add button:![Getting ready]()
-
In the code-behind file of
NorthwindService.asmx, uncomment the following statements at the top of the file to enable the service to be accessed by Ajax:
对于 VB,声明如下:
```
<System.Web.Script.Services.ScriptService()>
```
对于 c#,语句如下:
```
[System.Web.Script.Services.ScriptService]
```
- Add the following namespace at the top of file. This will enable us to pick the Northwind database connection string from the
web.configfile.
对于 VB,代码如下:
```
Imports System.Web.Configuration
```
对于 c#,代码如下:
```
using System.Web.Configuration;
```
- Next, add a
GetEmployeeResult()web method to the code-behind file.
对于 VB,代码如下:
```
<WebMethod()>
Public Function GetEmployeeResult(ByVal sSearch As String) As Employee()
Dim employeeList As List(Of Employee) = New List(Of Employee)()
Dim strConn As String = WebConfigurationManager.ConnectionStrings("NorthwindConnection").ConnectionString
Dim con As SqlConnection = New SqlConnection(strConn)
Dim strSql As String = "SELECT * FROM EMPLOYEES WHERE FirstName LIKE '%" + sSearch + "%' or LastName like '%" + sSearch + "%'"
Dim cmd As SqlCommand = New SqlCommand(strSql, con)
con.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader()
While (dr.Read())
Dim emp As Employee = New Employee()
emp.EmployeeID = dr("EmployeeID").ToString()
emp.FirstName = dr("FirstName").ToString()
emp.LastName = dr("LastName").ToString()
emp.City = dr("City").ToString()
emp.Country = dr("Country").ToString()
emp.HomePhone = dr("HomePhone").ToString()
employeeList.Add(emp)
End While
con.Close()
Return employeeList.ToArray()
End Function
```
对于 c#,代码如下:
```
[WebMethod]
public Employee[] GetEmployeeResult(String sSearch)
{
List<Employee> employeeList = new List<Employee>();
String strConn = WebConfigurationManager.ConnectionStrings["NorthwindConnection"].ConnectionString;
SqlConnection con = new SqlConnection(strConn);
String strSql = "SELECT * FROM EMPLOYEES WHERE FirstName LIKE '%" + sSearch + "%' or LastName like '%" + sSearch + "%'";
SqlCommand cmd = new SqlCommand(strSql, con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Employee emp = new Employee();
emp.EmployeeID = dr["EmployeeID"].ToString();
emp.FirstName = dr["FirstName"].ToString();
emp.LastName = dr["LastName"].ToString();
emp.City = dr["City"].ToString();
emp.Country = dr["Country"].ToString();
emp.HomePhone = dr["HomePhone"].ToString();
employeeList.Add(emp);
}
con.Close();
return employeeList.ToArray();
}
```
前面代码中定义的 web 方法从调用程序接收一个搜索关键字。 然后,它使用 ADO 连接到 Northwind 数据库.NET 并查询`Employees`表,以返回`FirstName`或`LastName`列包含搜索关键字的记录。 记录列表作为`Employee`类型的数组返回。
### 注意事项
请注意,调用程序需要将`sSearch`输入参数传递给 web 方法。
- 在
web.config文件的配置部分将连接字符串添加到 Northwind 数据库:
```
<connectionStrings>
<add name="NorthwindConnection" providerName="System.Data.SqlClient" connectionString="Data Source=localhost;Initial Catalog=Northwind;Integrated Security=True;"/>
</connectionStrings>
```
注意事项
请注意在本书中,我们对所有数据库驱动的示例都使用 Windows 身份验证。 因此,在 MS SQL Server 中,给 Windows 帐户访问 Northwind 数据库的权限是很重要的。
怎么做……
在页面的<script>块中包含以下 jQuery 代码:
$(document).ready(function () {
$("#tblResponse").hide();
$("#<%=lblMessage.ClientID%>").hide();
$("#<%=txtKeyword.ClientID%>").focus();
$("#<%=btnSearch.ClientID%>").on("click", function (evt) {
evt.preventDefault();
$("#<%=lblMessage.ClientID%>").hide();
var sKeyword = $("#<%=txtKeyword.ClientID%>").val().trim();
if (sKeyword != "") {
$.ajax({
url: "/Services/NorthwindService.asmx/GetEmployeeResult",
type: "POST",
data: '{ "sSearch": "' + sKeyword + '"}',
dataType: "json",
contentType: "application/json; charset=utf-8",
timeout: 5000,
cache: false,
success: function (response) {
$("#tblResponse tr:gt(0)").remove();
if ($("#tblResponse").is(":hidden"))
$("#tblResponse").show();
if (response.d.length > 0) {
$.each(response.d, function () {
("#tblResponse").append("<tr><td>" + this['EmployeeID'] + "</td><td>" + this['FirstName'] + "</td><td>" + this['LastName'] + "</td><td>" + this['City'] + "</td><td>" + this['Country'] + "</td><td>" + this['HomePhone'] + "</td></tr>");
});
} else $("#<%=lblMessage.ClientID%>").text("No results").show();
},
error: function (jqXHR, textStatus, errorThrown) {
if (textStatus == "error") {
alert("An error has occurred: " + jqXHR.status + " " + jqXHR.statusText);}
}
});
}
else
alert("Please enter your search keyword");
});
});
</script>
How it works…
对 web 服务的 Ajax 调用如下:
-
当页面启动时,将向用户显示一个文本字段,以便键入搜索关键字。 在页面上完成以下初始化:
-
结果表被隐藏,如下:
$("#tblResponse").hide(); -
用于显示信息/错误信息的标签被隐藏:
$("#<%=lblMessage.ClientID%>").hide(); -
光标聚焦在文本字段上,以便用户键入所需的搜索关键字:
$("#<%=txtKeyword.ClientID%>").focus();
-
-
An event handler is attached in order to respond to the
clickevent of the button on the page:$("#<%=btnSearch.ClientID%>").on("click", function (evt) {…});在此事件处理程序中,使用以下代码阻止页面返回:
evt.preventDefault();前面的查询可能会显示信息/错误消息,因此
lblMessage控件再次被隐藏:$("#<%=lblMessage.ClientID%>").hide();接下来,检索在文本字段中输入的搜索关键字。 白色空间,如果有,将被裁剪:
var sKeyword = $("#<%=txtKeyword.ClientID%>").val().trim();如果关键字不为空,则使用 HTTP POST 对 web 服务进行 Ajax 调用:
if (sKeyword != "") { $.ajax({ url: "/Services/NorthwindService.asmx/GetEmployeeResult", type: "POST", data: '{ "sSearch": "' + sKeyword + '"}', dataType: "json", contentType: "application/json; charset=utf-8", timeout: 5000, cache: false, success: function(response) { $("#tblResponse tr:gt(0)").remove(); if ($("#tblResponse").is(":hidden")) $("#tblResponse").show(); if (response.d.length > 0) { $.each(response.d, function() { $("#tblResponse").append("<tr><td>" + this['EmployeeID'] + "</td><td>" + this['FirstName'] + "</td><td>" + this['LastName'] + "</td><td>" + this['City'] + "</td><td>" + this['Country'] + "</td><td>" + this['HomePhone'] + "</td></tr>"); }); } else $("#<%=lblMessage.ClientID%>").text("No results ").show(); }, error: function(jqXHR, textStatus, errorThrown) { if (textStatus == "error") { alert("An error has occurred: " + jqXHR.status + " " + jqXHR.statusText); } } }); }在前面的 Ajax 调用中,设置了以下选项:
-
请求 URL 设置为
WebServicePath/WebMethodName。 -
HTTP 请求类型/方法设置为
POST。 -
数据由一个 JSON 格式的字符串组成。 搜索关键字使用名称/值对发送。 名称设置为
sSearch,值设置为从文本字段中检索到的字符串。 JSON 格式字符串如下:'{ "sSearch": "' + sKeyword + '"}' -
响应的预期数据类型设置为
json。 -
内容类型设置为
application/json,字符设置为utf-8。 -
指定了一个
5000毫秒的超时时间,以便如果服务器在此时间范围内未能响应,请求将终止。 -
缓存被设置为
false,因此响应不会缓存在浏览器中。 -
为成功完成 Ajax 调用指定了一个回调函数。 该函数首先清除所有先前显示的项目的显示表:
$("#tblResponse tr:gt(0)").remove(); -
如果表是隐藏的,它是可见的:
-
接下来,它检查响应是否为非空。 这可以通过检查
response.d的长度来实现。 如果响应非空,则显示响应数组中的每个项:if (response.d.length > 0) { $.each(response.d, function () { $("#tblResponse").append("<tr><td>" + this['EmployeeID'] + "</td><td>" + this['FirstName'] + "</td><td>" + this['LastName'] + "</td><td>" + this['City'] + "</td><td>" + this['Country'] + "</td><td>" + this['HomePhone'] + "</td></tr>"); }); } -
但是,如果响应为空,则使用
lblMessage控件显示一个错误,如下所示:
-
-
为不成功的 Ajax 调用指定一个回调函数。 在发生错误时,它显示
XmlHttpObject的status和statusText参数。 -
但是,如果用户单击按钮时搜索关键字为空,则向用户显示以下错误信息:
alert("Please enter your search keyword");
参见 also
消费 WCF 服务配方
使用 WCF 服务
消费 WCF 服务类似于消费 web 服务,如前面的配方中所述。 在本例中,我们将重做前面的配方,但这次使用的是 WCF 服务。 本例中使用的构造总结如下表:
|构造
|
类型
|
描述
|
| --- | --- | --- |
| $("#identifier") | jQuery 选择器 | 这将根据元素的 ID 选择一个元素。 |
| $("html_tag") | jQuery 选择器 | 这将选择具有指定 HTML 标记的所有元素。 |
| $.ajax() | jQuery 函数 | 这将向服务器发送一个带有设置选项的 Ajax 请求。 |
| .append() | jQuery 方法 | 这将在每个匹配元素的末尾插入内容。 |
| click | jQuery 的事件 | 当您单击一个元素时,它就会触发。 它对应于 JavaScript 的click事件。 |
| event. preventDefault() | jQuery 方法 | 这将防止触发事件的默认动作。 |
| .focus() | jQuery 事件绑定 | 这将触发元素的focus事件或将事件处理程序绑定到focus事件。 |
| :gt(i) | jQuery 选择器 | 这将选择索引大于i的匹配元素。 它使用了从零开始的索引。 |
| :hidden | jQuery 选择器 | 这将选择隐藏元素。 |
| .hide() | jQuery 方法 | 这将隐藏匹配的元素。 |
| .is() | jQuery 方法 | 如果匹配的元素满足给定条件,则返回一个布尔值。 |
| .on() | jQuery 事件绑定 | 这将一个或多个事件的事件处理程序附加到匹配的元素。 |
| .remove() | jQuery 方法 | 这会从 DOM 中删除匹配的元素。 |
| .show() | jQuery 方法 | 这会显示匹配的元素。 |
| .text() | jQuery 方法 | 这会返回每个匹配元素的组合文本内容,或者设置每个匹配元素的文本内容。 |
| .trim() | JavaScript 函数 | 这将删除字符串开头和结尾的空白。 |
| .val() | jQuery 方法 | 返回第一个匹配元素的值,或者设置每个匹配元素的值。 |
准备
按照的步骤来构建一个使用 WCF 服务的页面:
-
Similar to the previous recipe, the goal here is to search for employee records by the first or last name. When a match is found, the records are displayed, as shown in the following screenshot:
![Getting ready]()
如果没有找到匹配项,页面会向用户显示相应的消息:
![Getting ready]()
-
要创建此应用,请启动ASP.NET Web 应用项目在 Visual Studio 中使用空的模板,并将其命名为
Recipe4(或其他合适的名称)。 -
将 jQuery 库添加到项目中
Scripts文件夹中。 -
添加一个 web 表单到项目中,并在表单中包含 jQuery 库。
-
Include the following markup in the form:
<h3>Key in the Employee name to search:</h3> <asp:TextBox ID="txtKeyword" runat="server"></asp:TextBox> <asp:Button ID="btnSearch" runat="server" Text="Search" /> <br /><br /> <table id="tblResponse"> <thead> <tr> <th>Employee ID</th> <th>First Name</th> <th>Last Name</th> <th>City</th> <th>Country</th> <th>Home Phone</th> </tr> </thead> </table> <br /> <asp:Label ID="lblMessage" runat="server"></asp:Label>注意,表单有一个
Label控件lblMessage。 该字段将用于向用户显示信息/错误消息(如果有的话)。 -
使用下面的 CSS 样式来设置页面元素:
-
Add an
Employeeclass to the project by right-clicking on the project and navigating to Add | Class. Name the classEmployee.vb(VB) orEmployee.cs(C#). Add the following properties to the class.对于 VB,代码如下:
Public Class Employee Public Property EmployeeID As String Public Property LastName As String Public Property FirstName As String Public Property City As String Public Property Country As String Public Property HomePhone As String End Class对于 c#,代码如下:
public class Employee { public String EmployeeID { get; set; } public String LastName { get; set; } public String FirstName { get; set; } public String City{ get; set; } public String Country { get; set; } public String HomePhone { get; set; } } -
接下来,我们将向项目添加一个 WCF 服务。 要做到这一点,右键单击Solution Explorer选项卡中的项目,然后转到Add|New Folder。 将新文件夹命名为
Services。 -
Right-click on the
Servicesfolder and go to Add | New Item. From the launched dialog box, select Web from the Installed templates on the left-hand side of the screen. From the middle panel, select WCF Service (Ajax-enabled). Give the service a suitable name such asNorthwindService.svc, and click on the Add button:![Getting ready]()
-
In the code-behind file of
NorthwindService.svc, add the following namespace in order to enable us to retrieve the Northwind database connection string fromweb.config.
对于 VB,命名空间如下:
```
Imports System.Web.Configuration
```
对于 c#,命名空间如下所示:
```
using System.Web.Configuration;
```
- Next, add the
GetEmployeeResult()operation contract to the preceding code-behind file.
对于 VB,代码如下:
```
<OperationContract()>
Public Function GetEmployeeResult(ByVal sSearch As String) As Employee()
Dim employeeList As List(Of Employee) = New List(Of Employee)()
Dim strConn As String = WebConfigurationManager.ConnectionStrings("NorthwindConnection").ConnectionString
Dim con As SqlConnection = New SqlConnection(strConn)
Dim strSql As String = "SELECT * FROM EMPLOYEES WHERE FirstName LIKE '%" + sSearch + "%' or LastName like '%" + sSearch + "%'"
Dim cmd As SqlCommand = New SqlCommand(strSql, con)
con.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader()
While (dr.Read())
Dim emp As Employee = New Employee()
emp.EmployeeID = dr("EmployeeID").ToString()
emp.FirstName = dr("FirstName").ToString()
emp.LastName = dr("LastName").ToString()
emp.City = dr("City").ToString()
emp.Country = dr("Country").ToString()
emp.HomePhone = dr("HomePhone").ToString()
employeeList.Add(emp)
End While
con.Close()
Return employeeList.ToArray()
End Function
```
对于 c#,代码如下:
```
[OperationContract]
public Employee[] GetEmployeeResult(String sSearch)
{
List<Employee> employeeList = new List<Employee>();
String strConn = WebConfigurationManager.ConnectionStrings["NorthwindConnection"].ConnectionString;
SqlConnection con = new SqlConnection(strConn);
String strSql = "SELECT * FROM EMPLOYEES WHERE FirstName LIKE '%" + sSearch + "%' or LastName like '%" + sSearch + "%'";
SqlCommand cmd = new SqlCommand(strSql, con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Employee emp = new Employee();
emp.EmployeeID = dr["EmployeeID"].ToString();
emp.FirstName = dr["FirstName"].ToString();
emp.LastName = dr["LastName"].ToString();
emp.City = dr["City"].ToString();
emp.Country = dr["Country"].ToString();
emp.HomePhone = dr["HomePhone"].ToString();
employeeList.Add(emp);
}
con.Close();
return employeeList.ToArray();
}
```
操作契约从调用程序接收一个搜索关键字。 然后,它使用 ADO 连接到 Northwind 数据库.NET 并查询`Employees`表,以返回`FirstName`或`LastName`列包含搜索关键字的记录。 记录的列表作为`Employee`类型的数组返回。
### 注意事项
注意,调用程序需要将`sSearch`输入参数传递给 WCF 操作契约。
- 在
web.config文件的配置部分向 Northwind 数据库添加一个连接字符串:
```
<connectionStrings>
<add name="NorthwindConnection" providerName="System.Data.SqlClient" connectionString="Data Source=localhost;Initial Catalog=Northwind;Integrated Security=True;"/>
</connectionStrings>
```
注意事项
请注意,本书中所有数据库驱动的示例都使用 Windows 身份验证。 因此,在 MS SQL Server 中,给 Windows 帐户访问 Northwind 数据库的权限是很重要的。
怎么做……
在页面的<script>块中包含以下 jQuery 代码:
<script type="text/javascript">
$(document).ready(function() {
$("#tblResponse").hide();
$("#<%=lblMessage.ClientID%>").hide();
$("#<%=txtKeyword.ClientID%>").focus();
$("#<%=btnSearch.ClientID%>").on("click", function(evt) {
evt.preventDefault();
$("#<%=lblMessage.ClientID%>").hide();
var sKeyword = $("#<%=txtKeyword.ClientID%>").val().trim();
if (sKeyword != "") {
$.ajax({
url: "/Services/NorthwindService.svc/GetEmployeeResult",
type: "POST",
data: '{ "sSearch": "' + sKeyword + '"}',
dataType: "json",
contentType: "application/json; charset=utf-8",
timeout: 5000,
cache: false,
success: function(response) {
$("#tblResponse tr:gt(0)").remove();
if ($("#tblResponse").is(":hidden"))
$("#tblResponse").show();
if (response.d.length > 0) {
$.each(response.d, function() {
$("#tblResponse").append("<tr><td>" + this['EmployeeID'] + "</td><td>" + this['FirstName'] + "</td><td>" + this['LastName'] + "</td><td>" + this['City'] + "</td><td>" + this['Country'] + "</td><td>" + this['HomePhone'] + "</td></tr>");
});
} else
$("#<%=lblMessage.ClientID%>").text("No results").show();
},
error: function(jqXHR, textStatus, errorThrown) {
if (textStatus == "error") {
alert("An error has occurred: " + jqXHR.status + " " + jqXHR.statusText);
}
}
});
} else
alert("Please enter your search keyword");
});
});
</script>
How it works…
对 WCF 服务的 Ajax 调用如下:
-
当页面启动时,将向用户显示一个文本字段,用于键入搜索关键字。 在页面上完成以下初始化:
-
结果表最初使用以下方法隐藏:
-
用于显示信息/错误消息的 Label 字段也被隐藏:
$("#<%=lblMessage.ClientID%>").hide(); -
光标聚焦于文本字段,以便用户键入所需的关键字:
$("#<%=txtKeyword.ClientID%>").focus();
-
-
An event handler is defined to respond to the
clickevent of the button on the page:$("#<%=btnSearch.ClientID%>").on("click", function (evt) {…});在此事件处理程序中,使用以下方法阻止页面发回:
evt.preventDefault();前面的查询可能会显示信息/错误消息,因此
lblMessage控件再次被隐藏:$("#<%=lblMessage.ClientID%>").hide(); -
Next, the keyword entered in the text field is retrieved. Whitespaces, if any, are trimmed:
var sKeyword = $("#<%=txtKeyword.ClientID%>").val().trim();如果关键字不为空,则对 Web 服务进行 Ajax 调用:
if (sKeyword != "") { $.ajax({ url: "/Services/NorthwindService.svc/GetEmployeeResult", type: "POST", data: '{ "sSearch": "' + sKeyword + '"}', dataType: "json", contentType: "application/json; charset=utf-8", timeout: 5000, cache: false, success: function(response) { $("#tblResponse tr:gt(0)").remove(); if ($("#tblResponse").is(":hidden")) $("#tblResponse").show(); if (response.d.length > 0) { $.each(response.d, function() { $("#tblResponse").append("<tr><td>" + this['EmployeeID'] + "</td><td>" + this['FirstName'] + "</td><td>" + this['LastName'] + "</td><td>" + this['City'] + "</td><td>" + this['Country'] + "</td><td>" + this['HomePhone'] + "</td></tr>"); }); } else $("#<%=lblMessage.ClientID%>").text("No results").show(); }, error: function(jqXHR, textStatus, errorThrown) { if (textStatus == "error") { alert("An error has occurred: " + jqXHR.status + " " + jqXHR.statusText); } } }); }在前面的 Ajax 调用中,设置了以下选项:
-
请求 URL 被设置为 WCFPath/OperationContract。
-
HTTP 请求类型/方法设置为
POST。 -
数据由一个 JSON 格式的字符串组成。 搜索关键字以名称/值对的形式发送。 名称设置为
sSearch,值设置为从文本字段中检索到的字符串,如下所示: -
响应的预期数据类型设置为
json。 -
内容类型设置为
application/json,字符设置为utf-8。 -
指定了一个
5000毫秒的超时时间,以便如果服务器在此时间范围内未能响应,请求将终止。 -
缓存被设置为
false,因此响应不会缓存在浏览器中。 -
为成功完成 Ajax 调用指定了一个回调函数。 此功能首先清除显示表:
$("#tblResponse tr:gt(0)").remove(); -
如果表是隐藏的,那么它就是可见的。
if ($("#tblResponse").is(":hidden")) $("#tblResponse").show();
-
-
Next, it checks whether the response is nonempty. This can be done by checking the length of
response.d. If the response is nonempty, each item in the response array is displayed:if (response.d.length > 0) { $.each(response.d, function () { $("#tblResponse").append("<tr><td>" + this['EmployeeID'] + "</td><td>" + this['FirstName'] + "</td><td>" + this['LastName'] + "</td><td>" + this['City'] + "</td><td>" + this['Country'] + "</td><td>" + this['HomePhone'] + "</td></tr>"); }); }但是,如果响应为空,则使用
lblMessage控件显示错误:$("#<%=lblMessage.ClientID%>").text("No results").show(); -
为不成功的 Ajax 调用指定了一个回调函数。 在发生错误时,它显示
XmlHttpObject的status和statusText参数。 -
但是,如果用户单击
Button控件时搜索关键字为空,则向用户显示以下错误消息:alert("Please enter your search keyword");
参见 also
消费 Web 服务配方
从 Web API 中检索数据
Web API(Web 应用编程接口)是使用. net 框架创建的 HTTP API。 它使用 HTTP 协议返回数据。 由于 HTTP 可以在广泛的平台上使用,所以这些 api 可以在 Web 和移动平台上使用,也可以跨各种设备使用。
在这个例子中,我们将使用 jQuery Ajax 向 Web API 发布一个请求。 下表总结了本例中使用的结构:
|构造
|
类型
|
描述
|
| --- | --- | --- |
| $("#identifier") | jQuery 选择器 | 这将根据元素的 ID 选择一个元素。 |
| $("html_tag") | jQuery 选择器 | 这将选择具有指定 HTML 标记的所有元素。 |
| $.getJSON() | jQuery 函数 | 这将使用 HTTPGET请求从服务器加载 JSON 数据。 |
| .append() | jQuery 方法 | 这将在每个匹配元素的末尾插入内容。 |
| click | jQuery 的事件 | 当您单击一个元素时,它就会触发。 它对应于 JavaScript 的click事件。 |
| event. preventDefault() | jQuery 方法 | 这将防止触发事件的默认动作。 |
| .focus() | jQuery 事件绑定 | 这将触发元素的focus事件或将事件处理程序绑定到focus事件。 |
| :gt(i) | jQuery 选择器 | 这将选择索引大于i的匹配的元素。 它使用一个从零开始的索引。 |
| .hide() | jQuery 方法 | 这将隐藏匹配的元素。 |
| :hidden | jQuery 选择器 | 这将选择隐藏元素。 |
| .is() | jQuery 方法 | 如果匹配的元素满足给定条件,则返回一个布尔值。 |
| .on() | jQuery 事件绑定 | 这将一个或多个事件的事件处理程序附加到匹配的元素。 |
| .remove() | jQuery 方法 | 这会从 DOM 中删除匹配的元素。 |
| .show() | jQuery 方法 | 这会显示匹配的元素。 |
| .text() | jQuery 方法 | 这将返回每个匹配元素的组合文本内容,或者设置每个匹配元素的文本内容。 |
| .trim() | JavaScript 函数 | 这将删除字符串开头和结尾的空白。 |
| .val() | jQuery 方法 | 返回第一个匹配元素的值,或者设置每个匹配元素的值。 |
准备
按照以下步骤构建一个从 Web API 加载数据的页面:
-
Let's create a web page that allows you to search for customer records from the Northwind database using either
Customer IDorCustomer Name. When a match is found, the results are returned, as shown in the following screenshot:![Getting ready]()
如果没有匹配,则显示,如下图所示:
![Getting ready]()
-
To create this application, launch an ASP.NET Web Application project in Visual Studio using the Empty template and name it
Recipe5(or any other suitable name).注意事项
注意,我们在这个食谱中使用的是空的模板。 如果从可用的模板中选择了Web API,则使用 ASP 创建 API。 净 MVC。
-
将 jQuery 库添加到项目的
Scripts文件夹中。 -
添加一个 web 表单到项目中,并在表单中包含 jQuery 库。 在
head元素中,添加以下样式: -
Add a Model folder by right-clicking on the project in the Solution Explorer tab and navigating to Add | New Folder. Next, right-click on the Model folder and go to Add | Class. Name the class
Customer.vb(VB) orCustomer.cs(C#). Add the following properties to this file.对于 VB,代码如下:
Public Class Customer Public Property CustomerID As String Public Property CompanyName As String Public Property ContactName As String Public Property Phone As String Public Property Country As String End Class对于 c#,添加以下代码:
public class Customer { public String CustomerID { get; set;} public String CompanyName { get; set; } public String ContactName { get; set; } public String Country { get; set; } public String Phone { get; set; } } -
Add a Controllers folder by right-clicking on the project and navigating to Add | New Folder. Next, right-click on the Controllers folder and go to Add | Controller. Select Web API 2 Controller – Empty from the list of available templates, as shown in the following screenshot, and click on the Add button:
![Getting ready]()
在下一个对话框中,为控制器输入一个合适的名称。 我们将控制器命名为CustomerController:
![Getting ready]()
-
Open the code-behind file of
CustomerController, that is,CustomerController.vb(VB) orCustomerController.cs(C#) and add the following methods.对于 VB,代码如下:
' GET api/<controller>/keyword Public Function GetCustomers(ByVal searchKeyword As String) As IEnumerable(Of Customer) Dim customers As New List(Of Customer) Dim con As New SqlConnection(WebConfigurationManager.ConnectionStrings("NorthwindConnection").ConnectionString) Dim strQuery As String = "SELECT * FROM CUSTOMERS WHERE CUSTOMERID LIKE '%" + searchKeyword + "%' OR COMPANYNAME LIKE '%" + searchKeyword + "%'" Dim cmd As New SqlCommand(strQuery, con) con.Open() Dim reader As SqlDataReader = cmd.ExecuteReader() While (reader.Read()) Dim cust As New Customer() cust.CustomerID = reader("CustomerID").ToString() cust.CompanyName = reader("CompanyName").ToString() cust.ContactName = reader("ContactName").ToString() cust.Country = reader("Country").ToString() cust.Phone = reader("Phone").ToString() customers.Add(cust) End While con.Close() Return customers End Function ' GET api/<controller> Public Function GetAllCustomers() As IEnumerable(Of Customer) Dim customers As New List(Of Customer) Dim con As New SqlConnection(WebConfigurationManager.ConnectionStrings("NorthwindConnection").ConnectionString) Dim strQuery As String = "SELECT * FROM CUSTOMERS" Dim cmd As New SqlCommand(strQuery, con) con.Open() Dim reader As SqlDataReader = cmd.ExecuteReader() While (reader.Read()) Dim cust As New Customer() cust.CustomerID = reader("CustomerID").ToString() cust.CompanyName = reader("CompanyName").ToString() cust.ContactName = reader("ContactName").ToString() cust.Country = reader("Country").ToString() cust.Phone = reader("Phone").ToString() customers.Add(cust) End While con.Close() Return customers End Function对于 c#,代码如下所示:
public IEnumerable<Customer> GetCustomers(String searchKeyword) { List<Customer> customers = new List<Customer>(); SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["NorthwindConnection"].ConnectionString); String strQuery = "SELECT * FROM CUSTOMERS WHERE CUSTOMERID LIKE '%" + searchKeyword + "%' OR COMPANYNAME LIKE '%" + searchKeyword + "%'" ; SqlCommand cmd = new SqlCommand(strQuery, con); con.Open(); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Customer cust = new Customer(); cust.CustomerID = reader["CustomerID"].ToString(); cust.CompanyName = reader["CompanyName"].ToString(); cust.ContactName = reader["ContactName"].ToString(); cust.Country = reader["Country"].ToString(); cust.Phone = reader["Phone"].ToString(); customers.Add(cust); } con.Close(); return customers; } public IEnumerable<Customer> GetAllCustomers() { List<Customer> customers = new List<Customer>(); SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["NorthwindConnection"].ConnectionString); String strQuery = "SELECT * FROM CUSTOMERS"; SqlCommand cmd = new SqlCommand(strQuery, con); con.Open(); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Customer cust = new Customer(); cust.CustomerID = reader["CustomerID"].ToString(); cust.CompanyName = reader["CompanyName"].ToString(); cust.ContactName = reader["ContactName"].ToString(); cust.Country = reader["Country"].ToString(); cust.Phone = reader["Phone"].ToString(); customers.Add(cust); } con.Close(); return customers; }我们在 Web API 中定义了两个
GET方法。GetCustomers()方法接受searchKeyword字符串参数并返回 Northwind 数据库的Customer表中所有客户的列表,其中CustomerID或CustomerName列包含此关键字。 第二个GetAllCustomers()方法不接受参数,并返回Customer表中的全部记录集。另外,在文件的顶部添加以下名称空间。
对于 VB,命名空间如下:
Imports System.Web.Http Imports System.Data.SqlClient Imports System.Web.Configuration对于 c#,命名空间如下所示:
using System.Web.Http; using System.Data.SqlClient; using System.Web.Configuration; -
To connect to the Northwind database, add the following connection string to the configuration section of
web.config:<connectionStrings> <add name="NorthwindConnection" providerName="System.Data.SqlClient" connectionString="Data Source=localhost;Initial Catalog=Northwind;Integrated Security=True;"/> </connectionStrings>提示
记住要允许 Windows 帐户访问 Northwind 数据库。
-
Add the routing information to the Web API in the
Application_Startprocedure inGlobal.asax.对于 VB,代码如下:
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs) RouteTable.Routes.MapHttpRoute("CustomerApi", "api/{controller}/{searchKeyword}", defaults:=New With {.searchKeyword = System.Web.Http.RouteParameter.Optional}) End Sub对于 c#,代码如下:
protected void Application_Start(object sender, EventArgs e) { RouteTable.Routes.MapHttpRoute( name: "CustomerApi", routeTemplate: "api/{controller}/{searchKeyword}", defaults: new { searchKeyword = RouteParameter.Optional } ); }
这个暴露了 Web API 在api/controller/keyword的方法。
注意事项
如果RouteTable.Routes.MapHttpRoute不能识别方法,引用添加到System.Web.Http和System.Web.Http.WebHost议会通过右键单击解决方案资源管理器中项目选项卡并导航到添加|引用【显示】。
怎么做……
添加以下 jQuery 代码到页面的<script>块:
<script type="text/javascript">
$(document).ready(function() {
$("#tblResponse").hide();
$("#<%=lblMessage.ClientID%>").hide();
$("#<%=txtKeyword.ClientID%>").focus();
$("#<%=btnSearch.ClientID%>").on("click", function(evt) {
evt.preventDefault();
$("#<%=lblMessage.ClientID%>").hide();
var sKeyword = $("#<%=txtKeyword.ClientID%>").val().trim();
var uri = ((sKeyword == "") ? "api/customer" : "api/customer/" + sKeyword);
$.getJSON(uri).done(function(data) {
$("#tblResponse tr:gt(0)").remove();
if ($("#tblResponse").is(":hidden"))
$("#tblResponse").show();
if (data.length > 0) {
$.each(data, function(key, val) {
$("#tblResponse").append("<tr><td>" + val.CustomerID + "</td><td>" + val.CompanyName + "</td><td>" + val.ContactName + "</td><td>" + val.Phone + "</td><td>" + val.Country + "</td></tr>");
});
} else
$("#<%=lblMessage.ClientID%>").text("No results").show();
}).fail(function(jqXHR, textStatus, errorThrown) {
alert("An error has occurred: " + textStatus + " " + errorThrown);
});
});
});
</script>
How it works…
对 Web API 的 Ajax 调用是通过以下步骤进行的:
-
当页面加载时,结果表将对用户隐藏:
$("#tblResponse").hide(); -
用于向用户显示信息/错误消息的
label控件最初也是隐藏的:$("#<%=lblMessage.ClientID%>").hide(); -
接下来,光标聚焦于搜索关键字文本字段:
$("#<%=txtKeyword.ClientID%>").focus(); -
The page will call the Web API when you click on the Search button. Hence, we write an event handler for the
clickevent of this button:$("#<%=btnSearch.ClientID%>").on("click", function (evt) {…});在这个事件处理程序中,页面将被阻止发回,如下所示:
evt.preventDefault();接下来,用来显示信息/错误信息的标签被隐藏:
$("#<%=lblMessage.ClientID%>").hide();搜索关键字是从表单的文本字段中检索的。 如果有空白,它会被裁剪以删除:
var sKeyword = $("#<%=txtKeyword.ClientID%>").val().trim();Web API 提供了两个
GET方法:一个带参数,即GetCustomers()方法,另一个不带参数,即GetAllCustomers()方法。GetCustomers()方法可以在api/customer/searchKeyword访问,而GetAllCustomers()方法可以在api/customer访问。因此,根据是否提供关键字,我们分别设置两个 uri,如下所示:
var uri = ((sKeyword == "") ? "api/customer" : "api/customer/" + sKeyword); -
Now, we make the Ajax call to the Web API by sending a request to the URI set in the preceding code using the
$.getJSON()method:$.getJSON(uri)返回对象为成功和不成功的请求分别提供了
.done()和.fail()回调方法:.done(function (data){…}) .fail(function (jqXHR, textStatus, errorThrown) {…}); -
The preceding
.done()callback method clears the result table by deleting all the rows except the header row:$("#tblResponse tr:gt(0)").remove();如果结果表不可见,则显示给用户:
if ($("#tblResponse").is(":hidden")) $("#tblResponse").show();接下来,我们检查从 Web API 返回的数据对象的长度。 如果对象不为空,则打印每条记录,如下所示:
if (data.length > 0){ $.each(data, function (key, val) { $("#tblResponse").append("<tr><td>" + val.CustomerID + "</td><td>" + val.CompanyName + "</td><td>" + val.ContactName + "</td><td>" + val.Phone + "</td><td>" + val.Country + "</td></tr>"); }); }如果对象为空,只需向用户显示一条信息消息:
$("#<%=lblMessage.ClientID%>").text("No results").show(); -
在
.fail()回调方法中,显示jqXHR对象的status和statusText参数如下:
参见 also
消费页面方法配方
对控制器动作进行 Ajax 调用
Ajax 调用也可以对 ASP 中的Controller动作进行。 净 MVC 应用。 在这个例子中,让我们从一个视图向控制器动作发送一个请求。 本例中使用的结构总结如下表:
构造
|
类型
|
描述
|
| --- | --- | --- |
| $("#identifier") | jQuery 选择器 | 这将根据元素的 ID 选择一个元素。 |
| $.ajax() | jQuery 函数 | 这将向服务器发送一个带有设置选项的 Ajax 请求。 |
| change | jQuery 的事件 | 当元素的值发生变化时,就会触发此操作。 它对应于 JavaScript 的change事件。 |
| .on() | jQuery 事件绑定 | 这将一个或多个事件的事件处理程序附加到匹配的元素。 |
| .text() | jQuery 方法 | 这将返回每个匹配元素的组合文本内容,或者设置每个匹配元素的文本内容。 |
| .trim() | JavaScript 函数 | 这将删除字符串开头和结尾的空白。 |
| .val() | jQuery 方法 | 返回第一个匹配元素的值,或者设置每个匹配元素的值。 |
准备
遵循以下步骤创建一个 MVC 应用,它将使用 Ajax 向控制器动作发布一个请求:
-
Let's create a web page in ASP.NET MVC that returns the weather of a particular city. When the page is loaded, it displays a drop-down menu with a list of cities, as shown in the following screenshot:
![Getting ready]()
当从下拉菜单中选择特定城市时,从
Controller动作中检索天气信息并显示在页面上,如下图所示:![Getting ready]()
-
To create this application, launch an ASP.NET Web Application project in Visual Studio and name it
Recipe6(or any other suitable name). Select the Empty template and make sure that the MVC checkbox is selected, as shown in the following screenshot:![Getting ready]()
-
点击OK按钮继续。
-
将 jQuery 库添加到项目中
Scripts文件夹中。 -
In the Solution Explorer tab, right-click on the
Controllersfolder and go to Add | Controller. From the Add Scaffold dialog box that is launched, choose MVC5 Controller – Empty, and click on the Add button:![Getting ready]()
在以下对话框中命名控制器
HomeController,单击添加按钮:![Getting ready]()
-
In the code-behind file of
HomeController, you will notice that, by default, anActionResultmethod calledIndexis defined. Right-click on theIndexmethod, and click on the Add View... menu option, as shown in the following screenshot:![Getting ready]()
这个将启动Add View窗口,如下面的截图所示。 为视图名称文本字段输入
Index,选择空(无模型)模板。 取消选中Use a layout page选项,然后点击Add按钮:![Getting ready]()
-
打开
Index视图的代码后置文件并添加以下标记:<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>City Weather</title> <script src="~/Scripts/jquery-2.1.4.js"></script> <style type="text/css"> #divResult { font-variant: small-caps; color: blue; font-size: large; } </style> </head> <body> <form id="form1"> <div> <h3>Please select the city to see the current weather:</h3> <select id="ddlCities"> <option value="">--Please Select--</option> <option value="Dubai">Dubai</option> <option value="Hong Kong">Hong Kong</option> <option value="Mumbai">Mumbai</option> <option value="Perth">Perth</option> <option value="Singapore">Singapore</option> <option value="Wellington">Wellington</option> </select> </div> <br /> <div id="divResult"></div> </form> </body> </html> -
Add a
GetCityWeather()method to the code-behind file ofHomeControllerto return the weather of a particular city. This method will take in one parameter, that is, the city name, and return a string containing the weather information.对于 VB,代码如下:
Public Function GetCityWeather(ByVal sCity As String) As String Dim sWeather As String = String.Empty Select Case sCity Case "Dubai" sWeather = "Hot and sunny" Case "Hong Kong" sWeather = "Sunny" Case "Mumbai" sWeather = "Partially sunny" Case "Perth" sWeather = "Cloudy and windy" Case "Singapore" sWeather = "Hot and cloudy" Case "Wellington" sWeather = "Mostly cloudy" Case Else sWeather = "No weather information found" End Select Return sWeather End Function对于 c#,代码如下:
public string GetCityWeather(string sCity) { string sWeather = String.Empty; switch (sCity) { case "Dubai": sWeather = "Hot and sunny"; break; case "Hong Kong": sWeather = "Sunny"; break; case "Mumbai": sWeather = "Partially sunny"; break; case "Perth": sWeather = "Cloudy and windy"; break; case "Singapore": sWeather = "Hot and cloudy"; break; case "Wellington": sWeather = "Mostly cloudy"; break; default: sWeather = "No weather information found"; break; } return sWeather; }注意事项
注意控制器动作接受字符串类型的
sCity输入参数。 这个参数应该由 Ajax 请求中的客户机脚本提供。
怎么做……
将以下 jQuery 代码添加到视图的<script>块中:
<script type="text/javascript">
$(document).ready(function() {
$("#ddlCities").on("change", function() {
$("#divResult").text("");
var sCity = $(this).val().trim();
if (sCity != "") {
$.ajax({
url: "/Home/GetCityWeather",
type: "POST",
data: '{ "sCity": "' + sCity + '"}',
dataType: "text",
contentType: "application/json; charset=utf-8",
timeout: 5000,
cache: false,
success: function(response) {
$("#divResult").text("The weather in " + sCity + " is " + response);
},
error: function(jqXHR, textStatus, errorThrown) {
if (textStatus == "error") {
alert("An error has occurred: " + jqXHR.status + " " + jqXHR.statusText);
}
}
});
}
});
});
</script>
How it works…
向控制器发送 Ajax 请求的操作如下:
-
元素
div``divResult用于显示从控制器操作异步检索的天气信息。 -
The Ajax request is posted when the selected item in the dropdown changes. Hence, an event handler is written to respond to the
changeevent of the dropdown, as follows:$("#ddlCities").on("change", function () {…});在前面的事件处理程序中,首先清除
div元素的内容:$("#divResult").text("");检索所选城市的名称。 白色空间,如果有,将被裁剪:
var sCity = $(this).val().trim();如果城市名称不为空,则会向
controller动作发送一个 Ajax 请求,如下所示:if (sCity != ""){ $.ajax({ url: "/Home/GetCityWeather", type: "POST", data: '{ "sCity": "' + sCity + '"}', dataType: "text", contentType: "application/json; charset=utf-8", timeout: 5000, cache: false, success: function (response) { $("#divResult").text("The weather in " + sCity + " is " + response); }, error: function (jqXHR, textStatus, errorThrown) { if (textStatus == "error") { alert("An error has occurred: " + jqXHR.status + " " + jqXHR.statusText); } } }); }在前面的 Ajax 调用中,设置了以下选项:
-
请求 URL 设置为
Controller/Action。 -
HTTP 请求类型/方法设置为
POST。 -
数据由一个 JSON 格式的字符串组成。 选择的城市以名称/值对的形式发送,以
sCity作为名称,以下拉菜单中选择的值作为其值,如下:'{ "sCity": "' + sCity + '"}' -
响应的预期数据类型被设置为
text,因为controller操作发送的天气信息是字符串格式。 -
内容类型设置为
application/json,字符设置为utf-8。 -
指定了一个
5000毫秒的超时时间,以便如果服务器在此时间范围内未能响应,请求将终止。 -
缓存被设置为
false,因此响应不会缓存在浏览器中。 -
为成功完成 Ajax 调用指定了一个回调函数。 该功能仅在
div区域显示响应文本,如下所示: -
为不成功的 Ajax 调用指定一个回调函数。 在发生错误时,显示
XmlHttpObject的status和statusText参数:function (jqXHR, textStatus, errorThrown) { if (textStatus == "error") { alert("An error has occurred: " + jqXHR.status + " " + jqXHR.statusText); } }
-
参见 also
从 Web API 配方中检索数据
对 HTTP 处理程序进行 Ajax 调用
HTTP 处理程序是当请求特定资源时执行的进程。 例如,ASP.NET 提供了一个页面处理程序来处理*.aspx文件。 内建处理程序的另一个例子是用于处理*.asmx文件的 web 服务处理程序。
在这个配方中,让我们编写一个通用 HTTP 处理程序,它将向调用脚本返回自定义数据。 下表总结了本例中使用的结构:
|构造
|
类型
|
描述
|
| --- | --- | --- |
| $("#identifier") | jQuery 选择器 | 这将根据其 ID 选择一个元素 |
| $.ajax() | jQuery 函数 | 这将向服务器发送一个带有设置选项的 Ajax 请求 |
| $.map() | jQuery 函数 | 这将数组或对象转换为另一个数组 |
| .autocomplete() | jQuery UI 的方法 | 这将自动完成小部件附加到所需的元素 |
准备
遵循以下步骤构建一个页面,该页面将对 HTTP 处理程序进行 Ajax 调用:
-
Let's create a web page that provides an autocomplete text field. The values in the autocomplete are filtered dynamically using the characters entered in the text field, as shown in the following screenshot:
![Getting ready]()
注意,自动完成包含从 Northwind 数据库中的
Customers表的Country列中检索到的国家列表。 -
要创建此应用,请启动ASP.NET Web 应用项目在 Visual Studio 中使用空模板,并将其命名为
Recipe7(或任何其他合适的名称)。 -
Next, we will add a LINQ to SQL class to access data from the
Customerstable of the Northwind database. To do this, right-click on the project in Solution Explorer and go to Add | New Item. From the launched dialog box, select Data from the Installed templates from the left-hand side panel and LINQ to SQL classes from the middle panel. Name the itemNorthwind.dbml, and click on the Add button:![Getting ready]()
-
Connect to the Northwind database in Server Explorer and drag and drop the
Customerstable onNorthwind.dbml, as shown in the following screenshot:![Getting ready]()
-
Next, we will add the HTTP handler to the project. So, right-click on the project in Solution Explorer and go to Add | New Item. From the dialog box, click on the Web tab from the Installed templates in the left-hand side panel and Generic Handler in the middle panel. Enter the name
SearchKeys.ashxand click on the Add button:![Getting ready]()
-
In the code-behind file of the HTTP handler, add the following namespaces on the top.
对于 VB,命名空间如下:
Imports System.Data.Linq.SqlClient Imports System.Web.Script.Serialization对于 c#,命名空间如下所示:
using System.Data.Linq.SqlClient; using System.Web.Script.Serialization; -
Update the
SearchKeysclass to include aProcessRequestmethod, as follows.对于 VB,代码如下:
Public Class SearchKeys Implements System.Web.IHttpHandler Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest Dim strSearchText As String = context.Request.QueryString("sSearchText").Trim() Dim db As NorthwindDataContext = New NorthwindDataContext() Dim countryList As List(Of String) = (From cust In db.Customers Where SqlMethods.Like(cust.Country, "%" + strSearchText + "%") Select cust.Country).Distinct().ToList() Dim serializer As JavaScriptSerializer = New JavaScriptSerializer() Dim jsonString As String = serializer.Serialize(countryList) context.Response.Write(jsonString) End Sub ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable Get Return False End Get End Property End Class对于 c#,代码如下:
public class SearchKeys : IHttpHandler { public void ProcessRequest(HttpContext context) { string strSearchText = context.Request.QueryString["sSearchText"].Trim(); NorthwindDataContext db = new NorthwindDataContext(); List<string> countryList = (from cust in db.Customers where SqlMethods.Like(cust.Country, "%" + strSearchText + "%") select cust.Country).Distinct().ToList(); JavaScriptSerializer serializer = new JavaScriptSerializer(); string jsonString = serializer.Serialize(countryList); context.Response.Write(jsonString); } public bool IsReusable { get { return false; } } }注意事项
在前面的代码中创建的 HTTP 处理程序实现了
IHttpHander接口。 该接口要求处理程序实现IsReusable属性和ProcessRequest方法。 当调用处理程序时,将调用ProcessRequest方法。 因此,此方法包含生成必要输出的代码。IsReusable属性表明IHttpHandlerFactory(即调用处理程序的对象)可以将处理程序放入池中,并从池中重用它,以提高性能。 如果将此属性设置为false,则每次调用该处理程序时都会创建一个新的处理程序。方法接受一个类型为
HttpContext的参数。 使用Request.QueryString从该参数中提取搜索项。注意事项
注意,客户机脚本需要将搜索关键字作为名称为
sSearchText的查询字符串参数传递给处理程序。使用搜索关键字过滤
Customers表中的国家列表。 然后使用JavaScriptSerializer类的Serialize方法将列表序列化为 JSON 字符串。 -
Next, we will add the jQuery UI autocomplete widget to the project. To download this package using NuGet, from the menu at the top of the Visual Studio IDE, go to Project | Manage NuGet Packages. In the NuGet window, search for jQuery UI autocomplete, as shown in the following screenshot. Click on the Install button to install the package and its dependencies:
![Getting ready]()
注意,安装完成后,会创建
a Scripts文件夹,其中有一个文件列表,如下截图所示:![Getting ready]()
注意事项
保留 jQuery 的下载版本,以确保与 jQuery UI 文件的兼容性。
-
将 web 表单添加到项目中,在
head部分包含下载的脚本:<script src="Scripts/jquery-1.4.4.js"></script> <script src="Scripts/jquery.ui.core.js"></script> <script src="Scripts/jquery.ui.position.js"></script> <script src="Scripts/jquery.ui.widget.js"></script> <script src="Scripts/jquery.ui.autocomplete.js"></script> -
在表单中添加以下标记:
```
<div>
<h3>Autocomplete Search Box using AJAX</h3>
<asp:Label ID="lblSearchText" runat="server" Text="Key in the search item:"></asp:Label>
<asp:TextBox ID="txtSearchText" runat="server"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" />
</div>
```
- 在头部部分包含 jQuery UI 样式表。 此样式表可以从https://jqueryui.com:
```
<link href="Styles/jquery-ui.css" rel="stylesheet" />
```
下载
怎么做……
添加以下 jQuery 代码到页面的<script>块:
<script type="text/javascript">
$(document).ready(function() {
$("#<%=txtSearchText.ClientID%>").autocomplete({
source: function(request, response) {
$.ajax({
url: "SearchKeys.ashx?sSearchText=" + request.term,
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
timeout: 5000,
cache: false,
success: function(data) {
response($.map(data, function(item) {
return {
value: item
}
}));
},
error: function(jqXHR, textStatus, errorThrown) {
if (textStatus == "error") {
alert("An error has occurred: " + jqXHR.status + " " + jqXHR.statusText);
}
}
});
},
minLength: 1
});
});
</script>
How it works…
Ajax 请求的发送到 HTTP 处理程序的工作方式如下:
-
jQuery UI 自动完成小部件可以添加到接受输入的任何字段。 在本例中,小部件被添加到搜索文本字段,如下所示:
-
The
autocomplete()method provides asourceoption that can be set to an array, string, or function. In this case, we set thesourceto a function with two arguments, namely, arequestobject and aresponsecallback.请求对象有一个
term属性,该属性保存用户当前在该字段中键入的文本。 然后使用term属性作为查询字符串参数将 Ajax 请求发布到 HTTP 处理程序。 这个查询字符串参数被称为sSearchText,并在 HTTP 处理程序的ProcessRequest方法中检索:source: function(request,response){ $.ajax({ url: "SearchKeys.ashx?sSearchText=" + request.term, type: "POST", dataType: "json", contentType: "application/json; charset=utf-8", timeout: 5000, cache: false, success: function (data) { response($.map(data, function (item) { return { value: item } })); }, error: function (jqXHR, textStatus, errorThrown) { if (textStatus == "error") { alert("An error has occurred: " + jqXHR.status + " " + jqXHR.statusText); } } }); },在前面的 Ajax 调用中,设置了以下选项:
-
请求 URL 设置为
URLOfHTTPHandler?QueryStringParam=Request.term。 -
HTTP 请求的类型/方法设置为
POST。 -
响应的预期数据类型设置为
json。 -
内容类型设置为
application/json,字符设置为utf-8。 -
指定了一个
5000毫秒的超时时间,以便如果服务器在此时间范围内未能响应,请求将终止。 -
缓存被设置为
false,因此响应不会缓存在浏览器中。 -
为成功完成 Ajax 调用指定了一个回调函数。 该函数将响应回调的参数设置为,建议用户使用
$.map()函数,如下所示: -
为不成功的 Ajax 调用指定一个回调函数。 在发生错误时,显示
XmlHttpObject的status和statusText参数:function (jqXHR, textStatus, errorThrown) { if (textStatus == "error") { alert("An error has occurred: " + jqXHR.status + " " + jqXHR.statusText); } }
-
-
自动完成小部件还提供了
minLength选项来设置用户在触发搜索之前需要输入的字符数。 在本例中,我们将minLength选项设置为1字符,如下所示:
参见 also
对控制器操作配方进行 Ajax 调用
八、创建和使用 jQuery 插件
本章教你如何创建和使用插件。 本章讨论的配方如下:
- 创建和使用一个简单的插件
- 在插件中使用$别名
- 在 DOM 元素上调用方法
- 提供默认值
- 提供方法链接
- 向插件添加操作
- 使用表单验证插件
- 使用 NPM 下载插件
简介
jQuery 允许开发者通过创建插件来构建核心库的特性。 插件基本上是核心库的扩展。 它是一个 JavaScript 文件,包括在网页上的 jQuery 库。 它通常提供一组可配置项,开发人员可以根据其应用的需求使用这些项进行定制。
编写了各种各样的有用插件,可供使用。 它们涵盖了开发的许多方面,例如动画、图形、表单、UI 和响应性。 为了在一个集中的位置维护所有的插件,一个插件库于 2013 年在http://plugins.jquery.com发布。 然而,这个网站现在提供了对插件的只读访问,并且可以在NPM(Node Package Manager)上发布新版本。 插件可以从 NPM 下载和使用。
在本章中,让我们开始创建自己的插件。 我们还将下载并使用一个流行的 jQuery 插件来验证表单。
创建和使用一个简单的插件
在这个例子中,我们将编写一个简单的插件,让您熟悉创建和使用插件的过程。 本例中使用的编程结构总结如下:
|构造
|
类型
|
描述
|
| --- | --- | --- |
| .append() | jQuery 方法 | 这将在每个匹配元素的末尾插入内容 |
| jQuery | jQuery 函数 | 这是指 jQuery 函数 |
| jQuery("html_tag") | jQuery 选择器 | 这将选择具有指定 HTML 标记的所有元素 |
准备
按照以下步骤创建一个简单的 jQuery 插件:
-
启动一个新的ASP.NET Web 应用项目在 Visual Studio 中使用空模板,并将其命名为
TestApplication(或任何其他合适的名称)。 -
在项目中创建一个
Scripts文件夹。 将 jQuery 库文件添加到此文件夹。 -
Add a JavaScript file to the project by right clicking on the Scripts folder in the Solution Explorer tab and navigating to Add | JavaScript File. Name the file
jquery.sample.js. This is our plugin file to which we will add the custom functions to extend the jQuery library.注意事项
将插件命名为
jquery.{pluginname}.js是一个很好的做法。 -
向项目添加一个新的 web 表单,并将其命名为
Sample.aspx。 这个表单将用于从插件中调用函数。 -
在Source模式下打开
Sample.aspx页面,拖放 jQuery 库和插件文件,在head元素中生成以下代码:
怎么做……
在插件中使用$别名如下:
- 打开插件文件,在
jQuery命名空间中添加一个sampleMethod1()函数,如下代码片段所示: - 接下来,通过将下面的代码添加到
Sample.aspxweb 表单中,调用前面定义的函数:
How it works…
在浏览器中运行页面时,插件函数会在页面正文中显示以下文本:

由于该函数是在jQuery命名空间中定义的,所以可以直接在$对象上调用它。
注意事项
jQuery 库在jQuery命名空间中将许多实用函数定义为全局函数。 这些效用函数的一些例子是$.map()、$.each()和$.ajax()。
参见 also
使用插件配方中的$别名
*# 使用插件中的$别名
在这个示例中,让我们修改上一个配方中插件中定义的函数,以使用$别名而不是完整的jQuery名称。 使用$快捷方式提高了代码的可读性,但它的可用性并不能总是得到保证。 项目中的其他库也可能使用$。 使用$.noConflict()方法将 jQuery 对$的控制释放给其他库。
本例中使用的结构总结如下:
|构造
|
类型
|
描述
|
| --- | --- | --- |
| $ | jQuery 函数 | 这是指 jQuery 函数。 $是 jQuery 的别名。 |
| $("html_tag") | jQuery 选择器 | 这将选择具有指定 HTML 标记的所有元素。 |
| .append() | jQuery 方法 | 这将在每个匹配元素的末尾插入内容。 |
| jQuery | jQuery 函数 | 这是指 jQuery 函数。 |
准备
让我们看看在 jQuery 插件中使用$ alias 的要求:
-
我们将重用在前面的配方中创建的 web 表单(
Sample.aspx)和插件(jquery.sample.js)。 -
The plugin will be updated to include a wrapping function that takes
$as a parameter. ThejQueryobject will be passed as an argument to this function, as shown in the following code snippet:(function($){})(jQuery);通过传递
jQuery对象作为参数,可以在这个包装函数中使用$快捷方式。
怎么做……
按照以下步骤添加一个方法到插件:
-
用以下代码替换
jquery.sample.js文件中的代码:(function($) { $.sampleMethod2 = function() { $("body").append("Inside the sample 2 method"); }; })(jQuery); -
将
Sample.aspxweb 表单中的方法名称更改为,使用前面定义的方法名称:<script type="text/javascript"> $(document).ready(function () { $.sampleMethod2(); }); </script>
How it works…
在浏览器中运行该页面。 输出类似于前面的 recipe,也就是将需要的文本添加到页面的 body 中,如下截图所示:

由于该方法定义在jQuery名称空间中,因此可以直接在$快捷方式上调用它。
还有更多
在一个插件中可以定义多个函数。 要添加更多函数,只需将它们附加到包装函数内的原始插件文件中。 为了演示这一点,用以下代码更新jquery.sample.js文件:
(function ($) {
$.sampleMethod1 = function () {
$("body").append("Inside the sample 1 method<br/><br/>");
};
$.sampleMethod2 = function () {
$("body").append("Inside the sample 2 method<br/><br/>");
};
})(jQuery);
要在 web 表单中执行这些函数,请分别调用它们,如下代码片段所示:
<script type="text/javascript">
$(document).ready(function () {
$.sampleMethod1();
$.sampleMethod2();
});
</script>
在运行页面时,我们发现两个函数都执行了,如下截图所示:

参见 also
创建和使用一个简单的插件配方
调用 DOM 元素的方法
在前面的配方中,插件通过$快捷方式调用。 在这个食谱中,我们将创建一个可以直接在 DOM 元素上调用的插件。 这可以通过扩展jQuery.prototype,即jQuery.fn对象实现。
注意事项
JavaScript 中的每个对象都派生自Object,并从Object.prototype继承属性和方法。 当属性或方法附加到原型时,对象的所有实例都反映该属性或方法。
本例中使用的结构总结如下:
|构造
|
类型
|
描述
|
| --- | --- | --- |
| $ | jQuery 函数 | 这是指 jQuery 函数。 $是 jQuery 的别名。 |
| $("#identifier") | jQuery 选择器 | 这将根据元素的 ID 选择一个元素。 |
| $("html_tag") | jQuery 选择器 | 这将选择具有指定 HTML 标记的所有元素。 |
| $(this) | jQuery 对象 | 它引用当前 jQuery 对象。 |
| .css() | jQuery 方法 | 这将获取第一个匹配元素的 style 属性,或者设置每个匹配元素的 style 属性。 |
| .each() | jQuery 方法 | 这将遍历匹配的元素,并为每个元素执行一个函数。 |
| .hasClass() | jQuery 方法 | 如果指定的 CSS 类被附加到一个元素上,则返回 true。 |
| jQuery | jQuery 函数 | 这是指 jQuery 函数。 |
| setInterval(function, delay) | JavaScript 函数 | 这将在指定的延迟(以毫秒为单位)之后重复执行一个函数。 |
准备
按照以下步骤创建一个为 DOM 元素提供方法的插件:
-
Let's create a plugin that animates the text content of an element by switching its colors at regular intervals. For example, consider the following text on the page. At specific intervals, the color of the text will change to the colors in a rainbow (that is, violet, indigo, blue, green, yellow, orange, and red) one by one in a cyclic manner.
![Getting ready]()
-
使用之前创建的TestApplication项目,并添加一个新的 web 表单
Rainbow-1.0.aspx。 -
脚本文件夹,添加一个新的插件通过右键单击解决方案资源管理器中的文件夹选项卡并导航到|添加 JavaScript 文件【显示】,
jquery.rainbow-1.0.js插件名称。****
*** 通过从Solution Explorer标签页中拖放 jQuery 库和插件,在 web 表单中包含这些代码:<script src="Scripts/jquery-2.1.4.js"></script> <script src="Scripts/jquery.rainbow-1.0.js"></script>- 要对页面上的文本内容设置样式,请将以下 CSS 类添加到
head元素:* 在窗体上拖放一个Panel控件。 将前面定义的 CSS 类添加到Panel中。 另外,添加一些随机文本来生成以下标记:**
- 要对页面上的文本内容设置样式,请将以下 CSS 类添加到
**## 怎么做……
按照以下步骤向插件添加方法:
- 在插件文件中,添加一个名为
rainbow()的方法,如下代码所示: - 在
Rainbow-1.0.aspxweb 窗体中,调用Panel控件上的插件方法,如下所示:
How it works…
插件的工作原理如下:
-
In the plugin, we have created a
rainbow()method in the$.fnobject:(function ($) { $.fn.rainbow = function () {… }; })(jQuery);注意事项
$.fn是$.prototype的别名,即 jQuery 原型。 -
在此方法中,可以使用
this关键字var $ele = this;访问当前 DOM 元素。
-
接下来,定义一个数组
colors到遍历 DOM 元素:var colors = ["violet", "indigo", "blue", "green", "yellow", "orange", "red"]; -
使用变量将切换文本颜色的
interval设置为1000毫秒,其定义如下:var interval = 1000; -
计数器变量被初始化为零。 这个变量将跟踪当前从
colors数组显示的颜色:var cnt = 0; -
We use the JavaScript
setInterval()function to repeatedly refresh the color every1000milliseconds:setInterval(function () {…}, interval);在这个函数中,我们检查计数器是否超过了数组的长度。 如果是,则计数器被重置为零。 这是为了确保
colors以循环的方式应用于文本; 也就是说,在到达数组中的最后一个颜色后,第一个颜色被重复:if (cnt >= colors.length) cnt = 0;CSS属性color被更新为数组中的下一个颜色:$ele.css("color", colors[cnt]);计数器加 1 以获得数组中用于后续迭代的下一个颜色:
cnt++;
还有更多的…
到目前为止,我们已经定义了一个基本的插件方法。 然而,它是不完整的,还有许多改进的可能性。 为了演示一种可能的增强,向表单中添加另一个Panel,并添加一些随机文本,如下所示:
<asp:Panel ID="pnlTest" CssClass="sampleText" runat="server">
Text inside a Panel control
</asp:Panel>
<br /><br />
<asp:Panel ID="pnlTestNew" runat="server">Text inside a new Panel control
</asp:Panel>
注意,CSS 类sampleText没有应用于新的Panel控件。
让我们假设在插件方法中,我们希望有选择地只将动画应用到那些 CSS 类sampleText应用到它们的元素上。 因此,我们将更新方法来包含这个条件,如下所示:
(function($) {
$.fn.rainbow = function() {
var $ele = this;
if ($ele.hasClass("sampleText")) {
var colours = ["violet", "indigo", "blue", "green",
"yellow", "orange", "red"
];
var interval = 1000;
var cnt = 0;
setInterval(function() {
if (cnt >= colours.length)
cnt = 0;
$ele.css("color", colours[cnt]);
cnt++;
}, interval);
}
};
})(jQuery);
现在,通过使用 HTML 选择器调用Panel控件上的插件方法再次运行页面。 注意,这个选择器匹配多个元素:
$("div").rainbow();
输出如下面的截图所示。 注意,动画不是只应用于第一个Panel,而是错误地应用于两个Panel控件:

这是因为包含了.hasClass("sampleText")条件,该条件返回 DOM 中第一个匹配元素的检查结果。
为了确保插件方法正确地应用于所有元素,建议将方法包含在.each()中。 因此,将前面的代码修改为以下代码:
(function($) {
$.fn.rainbow = function() {
this.each(function() {
var $ele = $(this);
if ($ele.hasClass("sampleText")) {
var cnt = 0;
var colours = ["violet", "indigo", "blue", "green",
"yellow", "orange", "red"
];
var interval = 1000;
setInterval(function() {
if (cnt >= colours.length)
cnt = 0;
$ele.css("color", colours[cnt]);
cnt++;
}, interval);
}
});
};
})(jQuery);
因此,动画将被应用到具有 CSS 类sampleText的元素上,即第一个Panel控件,如下图所示:

参见 also
提供默认值配方
提供默认值
在插件方法中提供可配置项,使开发人员能够根据应用的需求进行定制,这是一个很好的实践。 使用options对象使我们能够实现这一点。 还可以提供一组默认的选项,以便开发人员可以有选择地覆盖他们想要的配置。
在这个例子中,让我们构建在前面的配方中创建的插件,以提供选项对象以及默认值的映射。
本例中使用的结构总结如下:
|构造
|
类型
|
描述
|
| --- | --- | --- |
| $ | jQuery 函数 | 这是指 jQuery 函数。 $是 jQuery 的别名。 |
| $("#identifier") | jQuery 选择器 | 这将根据元素的 ID 选择一个元素。 |
| $(this) | jQuery 对象 | 它引用当前 jQuery 对象。 |
| $.extend() | jQuery 函数 | 这将两个或多个对象的内容合并到第一个对象中。 |
| .css() | jQuery 方法 | 这将获取第一个匹配元素的 style 属性,或者设置每个匹配元素的 style 属性。 |
| .each() | jQuery 方法 | 这个遍历匹配的元素,并为每个元素执行一个函数。 |
| .hasClass() | jQuery 方法 | 如果指定的 CSS 类被附加到一个元素上,则返回 true。 |
| jQuery | jQuery 函数 | 这是指 jQuery 函数。 |
| setInterval(function, delay) | JavaScript 函数 | 这将在指定的延迟(以毫秒为单位)之后重复执行一个函数。 |
准备
按照以下步骤创建一个 web 表单来调用插件方法的默认值:
-
为了将代码与前面的配方分开,让我们在TestApplication项目中创建另一个名为
Rainbow-1.1.aspx的 web 表单。 -
通过右键单击Solution Explorer选项卡中的Scripts文件夹,并导航到Add|JavaScript File,添加另一个插件。 命名
jquery.rainbow-1.1.js文件。 -
在Source模式下打开
Rainbow-1.1.aspx,在页面的head元素中拖放 jQuery 库和插件,生成如下代码:<script src="Scripts/jquery-2.1.4.js"></script> <script src="Scripts/jquery.rainbow-1.1.js"></script> -
要样式化页面上的文本,添加以下 CSS 类:
<style type="text/css"> .sampleText{ font-family:'Times New Roman', Times, serif; font-size:30px; } </style> -
在 web 窗体上拖放一个Panel控件。 添加前面的 CSS 类和一些随机文本:
怎么做……
在插件文件中添加下面的代码:
(function($) {
$.fn.rainbow = function(opts) {
var defaults = {
colors: ["violet", "indigo", "blue", "green", "yellow", "orange", "red"],
interval: 1000
};
var options = $.extend(defaults, opts);
this.each(function() {
var $ele = $(this);
var cnt = 0;
setInterval(function() {
if (cnt >= options.colors.length)
cnt = 0;
$ele.css("color", options.colors[cnt]);
cnt++;
}, options.interval);
});
};
})(jQuery);
通过添加以下代码从 web 表单调用插件。 注意,我们提供了一个数组colors和一个以毫秒为单位的间隔来覆盖默认配置:
<script type="text/javascript">
$(document).ready(function () {
$("#<%=pnlTest.ClientID%>").rainbow({
colours: ["red", "blue", "green"],
interval: 2000
});
});
</script>
How it works…
插件方法的工作原理如下:
-
更新了插件方法
rainbow(),使其以一个名为opts的映射作为参数:(function($) { $.fn.rainbow = function(opts) {…} }; })(jQuery) -
提供了一个默认的映射,以适应没有提供或提供某些可配置值的场景。 如下代码片段所示,该插件有两个可配置项,即一个由
colors和interval组成的数组,用于颜色切换:var defaults = { colors: ["blue", "green", "yellow", "orange", "red"], interval:1000 }; -
Next, merge the
defaultsandoptsmaps using the jquery$.extend()function, as follows:var options = $.extend(defaults, opts);这里,修改了
defaults对象,并且覆盖了它与opts对象共享的任何属性。 将新属性添加到defaults对象。 如果defaults对象为空,则返回的目标对象将与opts对象相同。 -
Next, for each calling element, execute a function, as follows:
this.each(function () {…}在前面的函数中,首先,获取当前元素:
var $ele = $(this);把计数器设为零。 这个计数器将跟踪当前使用的颜色:
var cnt = 0;使用
setInterval()函数在步骤 3 中options对象指定的interval处执行一个函数。 如果调用元素没有提供interval,它将使用默认的interval。 注意,colors也是从options对象中读取的。 如果调用页面没有提供colors,则使用默认的colors:setInterval(function() { if (cnt >= options.colors.length) cnt = 0; $ele.css("color", options.colors[cnt]); cnt++; }, options.interval);
还有更多的…
可以通过多种方式调用插件方法。 由于参数是可选的,用户可以选择传递 none 或有选择地传递其中一些参数,如下代码所示:
$("#<%=pnlTest.ClientID%>").rainbow();
或
$("#<%=pnlTest.ClientID%>").rainbow({
colours: ["red", "blue", "green"]
});
或
$("#<%=pnlTest.ClientID%>").rainbow({
interval:1000
});
参见 also
链接配方的提供方法
提供方法链接
在 jQuery 中进行编程时,链接多个方法是非常有用的特性。 链接是可能的,因为大多数 jQuery 方法返回一个对象,允许在返回的对象上调用其他方法。 因为子方法是在返回的对象中而不是在整个 DOM 中执行的,所以代码运行得更快。 这允许您编写代码,这不仅更短,而且更快。
我们目前使用的插件不支持链接。 在本例中,让我们修改插件以包含该特性。
本例中使用的编程结构总结如下:
|构造
|
类型
|
描述
|
| --- | --- | --- |
| $ | jQuery 函数 | 这是指 jQuery 函数。 $是 jQuery 的别名。 |
| $("#identifier") | jQuery 选择器 | 此基于其ID选择元素。 |
| $(this) | jQuery 对象 | 它引用当前 jQuery 对象。 |
| $.extend() | jQuery 函数 | 这将两个或多个对象的内容合并到第一个对象中。 |
| .addClass() | jQuery 方法 | 这将为每个匹配的元素添加指定的 CSS 类。 |
| .css() | jQuery 方法 | 这将获取第一个匹配元素的 style 属性,或者设置每个匹配元素的 style 属性。 |
| .each() | jQuery 方法 | 这将遍历匹配的元素,并为每个元素执行一个函数。 |
| .find() | jQuery 方法 | 这将查找与筛选器匹配的所有元素。 |
| .hasClass() | jQuery 方法 | 如果指定的 CSS 类被附加到一个元素上,则返回 true。 |
| jQuery | jQuery 函数 | 这是指 jQuery 函数。 |
| setInterval(function, delay) | JavaScript 函数 | 这将在指定的延迟(以毫秒为单位)之后重复执行一个函数。 |
准备
按照以下步骤创建一个使用修改后的插件的网页:
-
在前面创建的
TestApplication项目中,添加一个名为Rainbow-1.2.aspx的新 web 表单。 -
通过右键单击Solution Explorer选项卡中的Scripts文件夹,并导航到Add|JavaScript file,添加新的插件文件。 将文件命名为
jquery.rainbow-1.2.js。 -
将 jQuery 库和插件拖放到表单中,生成以下标记:
<script src="Scripts/jquery-2.1.4.js"></script> <script src="Scripts/jquery.rainbow-1.2.js"></script> -
进入工具箱|Standard,将
Panel和Table控件添加到窗体中。 向控件中添加一些随机内容,以生成以下标记:<asp:Panel ID="pnlTest" runat="server" CssClass="sampleText"> Text inside a Panel control </asp:Panel> <br /><br /> <asp:Table ID="tblTest" runat="server"> <asp:TableHeaderRow> <asp:TableHeaderCell>Title</asp:TableHeaderCell> <asp:TableHeaderCell>Author</asp:TableHeaderCell> <asp:TableHeaderCell>Category</asp:TableHeaderCell> </asp:TableHeaderRow> <asp:TableRow> <asp:TableCell>The Alchemist</asp:TableCell> <asp:TableCell>Paulo Coelho</asp:TableCell> <asp:TableCell>Fiction</asp:TableCell> </asp:TableRow> <asp:TableRow> <asp:TableCell>You Can Win</asp:TableCell> <asp:TableCell>Shiv Khera</asp:TableCell> <asp:TableCell>Non-Fiction</asp:TableCell> </asp:TableRow> </asp:Table> -
为样式化
Panel控件中的文本,添加以下 CSS 类: -
要设置
Table控件的样式,请向表元素添加以下 CSS 样式: -
要设置表头的样式,请包含以下样式。 稍后,它将通过链接代码添加到表头:
.headerStyle{ font-weight:700; font-variant:small-caps; text-align:center; background-color:lightgray; padding:5px; }
怎么做……
更新插件如下:
-
在插件文件
jquery.rainbow-1.2.js中,添加以下代码: -
在
Rainbow-1.2.aspxweb 窗体的Panel和Table控件上调用插件方法。 将连锁方法添加到插件方法中,以测试连锁是否按要求工作:<script type="text/javascript"> $(document).ready(function() { $("#<%=pnlTest.ClientID%>").rainbow({ interval: 2000 }).css("backgroundColor", "lightyellow"); $("#<%=tblTest.ClientID%>").rainbow().find("th").addClass(" headerStyle"); }); </script>
How it works…
链接工作如下:
-
为了让链接工作,插件方法需要向调用代码返回一个
jQuery对象。 这可以通过更新插件来添加return关键字来实现,如下所示: -
现在,当在
Panel控件上调用rainbow()方法时,我们可以在以下语句中链接.css()方法来更改背景颜色:$("#<%=pnlTest.ClientID%>").rainbow({interval:2000}).css("b ackgroundColor","lightyellow"); -
Similarly, when the
rainbow()method is called on theTablecontrol, we can chain the.find()method to only filter the table header, that is,throws, and add the CSS classheaderStyleto it, as we did in the following statement:$("#<%=tblTest.ClientID%>").rainbow().find("th").addClass(" headerStyle");因此,颜色转换和样式更新应用于窗体上的两个控件,如下面的截图所示:
![How it works…]()
参见 also
提供默认值配方
向插件添加操作
在这个的例子中,让我们创建一个插件,通过将所需的操作作为参数来执行多个操作。 本例中使用的编程结构总结如下:
|构造
|
类型
|
描述
|
| --- | --- | --- |
| $("#identifier") | jQuery 选择器 | 这将根据元素的 ID 选择一个元素 |
| $(this) | jQuery 对象 | 它引用当前 jQuery 对象 |
| $.extend() | jQuery 函数 | 这将两个或多个对象的内容合并到第一个对象中 |
| . animate() | jQuery 方法 | 这将对指定的 CSS 属性执行自定义动画 |
| .css() | jQuery 方法 | 这将获取第一个匹配元素的 style 属性,或者设置每个匹配元素的 style 属性 |
| .each() | jQuery 方法 | 这将遍历匹配的元素,并为每个元素执行一个函数 |
| setInterval(function, delay) | JavaScript 函数 | 这将在指定的延迟(以毫秒为单位)之后重复执行一个函数 |
准备
按照以下步骤创建一个 web 表单,用于在插件方法上调用不同的操作:
-
In this recipe, let's create a plugin that can perform different types of effects on text content. We will focus on three effects: blink, color transition, and pulsation, as shown in the following screenshot:
![Getting ready]()
-
为了开始,在
TestApplication项目中,创建一个名为TextEffects.aspx的新 web 表单。 -
通过右键单击Solution Explorer选项卡,并导航到Add|JavaScript file,将一个新的插件文件添加到Scripts文件夹。 将文件命名为
jquery.texteffects.js。 -
以以下形式包含 jQuery 库和插件:
<script src="Scripts/jquery-2.1.4.js"></script> <script src="Scripts/jquery.texteffects.js"></script> -
从工具箱中拖放三个
Label控件。 标记如下:<asp:Label ID="lblTest1" runat="server" Text="This text will blink"></asp:Label><br /><br /> <asp:Label ID="lblTest2" runat="server" Text="This text will change colours"></asp:Label><br /><br /> <asp:Label ID="lblTest3" runat="server" Text="This text will pulsate"></asp:Label> -
在运行时,
Label控件作为span元素呈现。 因此,要设置Label控件的样式,请将以下样式添加到页面:span{ font-family:'Times New Roman', Times, serif; font-size:30px; }
怎么做……
更新插件和 web 表单如下所示:
-
在插件文件中添加以下代码:
(function($) { $.fn.texteffects = function(action, opts) { if (action == "blink") { var defaults = { interval: 1000 }; var options = $.extend(defaults, opts); var halfInterval = options.interval / 2; return this.each(function() { var $ele = $(this); setInterval(function() { $ele.animate({ opacity: 0 }, halfInterval).animate({ opacity: 1 }, halfInterval); }, options.interval); }); } else if (action == "pulsate") { var defaults = { minSize: "20", maxSize: "40", interval: 2000 }; var options = $.extend(defaults, opts); var halfInterval = options.interval / 2; return this.each(function() { var $ele = $(this); setInterval(function() { $ele.animate({ fontSize: options.maxSize + "px" }, halfInterval).animate({ fontSize: options.minSize + "px" }, halfInterval); }, options.interval); }); } else if (action == "rainbow") { var defaults = { colors: ["violet", "indigo", "blue", "green", "yellow", "orange", "red"], interval: 1000 }; var options = $.extend(defaults, opts); return this.each(function() { var $ele = $(this); var cnt = 0; setInterval(function() { if (cnt >= options.colors.length) cnt = 0; $ele.css("color", options.colors[cnt]); cnt++; }, options.interval); }); } }; })(jQuery); -
在的
TextEffects.aspx腹板中,第一次Label上的blink动作控制:$("#<%=lblTest1.ClientID%>").texteffects("blink"); -
在第二个
Label控制上调用rainbow动作:$("#<%=lblTest2.ClientID%>").texteffects("rainbow", { interval: 2000 }); -
在第三个 T1 上调用
pulsate动作:$("#<%=lblTest3.ClientID%>").texteffects("pulsate",{ maxSize: 50, minSize: 30, interval: 3000 });
How it works…
在插件方法上调用不同的操作如下:
-
插件方法接受两个参数:所需的
action和选项映射。 -
在这个插件中定义了三个操作:
blink、rainbow和pulsate。 使用传递给方法的action参数,可以调用相应的操作,如下面的代码片段所示: -
Within the
blinkaction, the default value for the blinkingintervalis set using a map:var defaults = { interval: 1000 };默认值与开发人员从调用页面传递的选项合并:
var options = $.extend(defaults, opts);在指定的时间间隔内,文本将淡出和淡入。 因此,一个半间隔被定义在其中文本的不透明度将被动画为零。 在剩余的半间隔中,文本的不透明度将被动画恢复为统一:
var halfInterval = options.interval / 2;为了启用链接,我们使用
return关键字将一个 jQuery 对象返回给调用代码,如下所示:return this.each(function () { var $ele = $(this); setInterval(function () { $ele.animate({ opacity: 0 }, halfInterval).animate({ opacity: 1 }, halfInterval); }, options.interval); });JavaScript 函数使用
setInterval()以指定的时间间隔重复从options.interval读取的进程。 两个连续的动画链接到元素上,如下所示:$ele.animate({ opacity: 0 }, halfInterval).animate({ opacity: 1 }, halfInterval);每个动画的持续时间设置为
halfInterval。 -
Within the pulsate action, the default values for the minimum and maximum font size and the
intervalof repetition are set using a map, as follows:var defaults = { minSize: "20", maxSize: "40", interval: 2000 };默认值与开发人员从调用页面提供的
options合并:var options = $.extend(defaults, opts);定义了半区间。 在前半部分间隔期间,字体大小会被动画化,从而增大到最大大小。 在第二个半间隔期间,字体大小被动画化,以便它减少到最小定义的大小:
var halfInterval = options.interval / 2;接下来,我们使用
return关键字将一个 jQuery 对象返回给调用代码,如下所示:return this.each(function () { var $ele = $(this); setInterval(function () { $ele.animate({ fontSize: options.maxSize + "px" }, halfInterval).animate({ fontSize: options.minSize + "px" }, halfInterval); }, options.interval); });通过使用
setInterval()JavaScript 函数可以重复动画。 该过程按options.interval指定的持续时间重复进行。 两个连续的动画链接到元素上,如下所示:$ele.animate({ fontSize: options.maxSize + "px" }, halfInterval).animate({ fontSize: options.minSize + "px" }, halfInterval);每个动画的持续时间设置为
halfInterval。 -
Within the
rainbowaction, we will update the color of the text at regular intervals. Thecolorsare read from an array. The default list ofcolorsand theintervalof thecolorswitch is defined in the following map:var defaults = { colors: ["violet", "indigo", "blue", "green", "yellow", "orange", "red"], interval: 1000 };默认值与开发人员从调用页面提供的实际
options合并:var options = $.extend(defaults, opts);为了启用链,我们使用
return关键字并返回一个 jQuery 对象到调用页面,如下代码所示:return this.each(function () { var $ele = $(this); var cnt = 0; setInterval(function () { if (cnt >= options.colors.length) cnt = 0; $ele.css("color", options.colors[cnt]); cnt++; }, options.interval); });JavaScript 函数
setInterval()用于在options.interval指定的持续时间内切换颜色。 元素的CSS属性color被更新并设置为数组中的当前颜色,如下所示:$ele.css("color", options.colors[cnt]);如果我们到达数组的末尾,颜色将被循环,我们可以再次从数组中的第一个颜色开始:
if (cnt >= options.colors.length) cnt = 0;在开始下一个迭代之前,计数器将被加 1 以从数组中检索下一个
color。
参见 also
使用表单验证插件配方
使用表单验证插件
其他开发人员编写的插件可以从中央插件库https://plugins.jquery.com中搜索和下载。 在搜索validation关键字时,我们遇到了由Jörn Zaefferer于 2006 年编写的 jQuery 验证插件,他是 jQuery 核心团队的成员之一。 插件的官方网站为http://jqueryvalidation.org。
在这个例子中,让我们下载并在我们的应用中使用这个插件。 本例中使用的编程结构总结如下:
|构造
|
类型
|
描述
|
| --- | --- | --- |
| $("#identifier") | jQuery 选择器 | 这将根据元素的 ID 选择一个元素。 |
| $("html_tag") | jQuery 选择器 | 这将选择具有指定 HTML 标记的所有元素。 |
| click | jQuery 的事件 | 当您单击一个元素时,它就会触发。 它对应于 JavaScript 的click事件。 |
| .closest() | jQuery 方法 | 对于每个匹配的元素,这将通过向上遍历 DOM 树返回与选择器匹配的第一个元素。 |
| event.preventDefault() | jQuery 方法 | 这将防止触发事件的默认动作。 |
| .hide() | jQuery 方法 | 这将隐藏匹配的元素。 |
| .html() | jQuery 方法 | 这将返回第一个匹配元素的 HTML 内容,或者设置每个匹配元素的 HTML 内容。 |
| .insertAfter() | jQuery 方法 | 这将在目标之后插入元素。 |
| .on() | jQuery 事件绑定 | 这将一个或多个事件的事件处理程序附加到匹配的元素。 |
| .prop(propertyName)或.prop(propertyName, value) | jQuery 方法 | 这将为第一个匹配的元素返回指定属性的值,或者为所有匹配的元素设置指定属性的值。 |
| .resetForm() | 验证插件的方法 | 这将重置表单的验证。 |
| .show() | jQuery 方法 | 这会显示匹配的元素。 |
| .siblings() | jQuery 方法 | 这个检索匹配元素的同族元素。 |
| .val() | jQuery 方法 | 返回第一个匹配元素的值,或者设置每个匹配元素的值。 |
| .validate() | 验证插件的方法 | 这将验证表单并返回一个验证器对象。 |
准备
要在 web 表单上使用验证插件,请遵循以下步骤:
-
The first step is to download the validation plugin, which can be obtained in many ways. It can be downloaded from the official website at http://jqueryvalidation.org. It is also available from package managers, such as Bower or NuGet. Alternatively, it can be referenced from CDN.
注意事项
要使用 Bower 下载它,请参考使用 NPM 配方下载插件。
![Getting ready]()
-
In the TestApplication project, let's download the plugin from NuGet. To launch NuGet, in the File menu, go to Tools | NuGet Package Manager | Manage NuGet Packages for Solution. In the NuGet screen, as shown in the following screenshot, search for
jquery validation. Select jQuery.Validation, and click on the Install button:![Getting ready]()
安装完成后,您会注意到以下文件被添加到Scripts文件夹中:
![Getting ready]()
-
将添加到项目中,并将其命名为
FormValidation.aspx。 在表单中包含 jQuery 库和验证插件,如下所示: -
Create a registration form that accepts different types of data, such as the text, e-mail, password, and so on, as shown in the following screenshot:
![Getting ready]()
使用以下标记创建表单:
<form id="frmRegistration" runat="server"> <h2>Registration Form</h2> <div id="summary"></div> <br /> <table> <tr> <td> <asp:Label ID="lblName" runat="server" Text="Name"></asp:Label><span class="mandatory">*</span></td> <td> <asp:TextBox ID="txtName" runat="server"></asp:TextBox> </td> </tr> <tr> <td> <asp:Label ID="lblEmail" runat="server" Text="Email"></asp:Label><span class="mandatory">*</span></td> <td> <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox> </td> </tr> <tr> <td> <asp:Label ID="lblPassword" runat="server" Text="Password"></asp:Label><span class="mandatory">*</span></td> <td> <asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox> </td> </tr> <tr> <td> <asp:Label ID="lblConfirmPassword" runat="server" Text="Confirm Password"></asp:Label><span class="mandatory">*</span></td> <td> <asp:TextBox ID="txtConfirmPassword" runat="server" TextMode="Password"></asp:TextBox> </td> </tr> <tr> <td> <asp:Label ID="lblDOB" runat="server" Text="Date of Birth"></asp:Label> </td> <td> <asp:TextBox ID="txtDOB" runat="server"></asp:TextBox> </td> </tr> <tr> <td> <asp:Label ID="lblMailAddr" runat="server" Text="Mailing Address"></asp:Label> </td> <td> <asp:TextBox ID="txtMailAddr" runat="server"></asp:TextBox> </td> </tr> <tr> <td> <asp:Label ID="lblPostal" runat="server" Text="Postal Code"></asp:Label> </td> <td> <asp:TextBox ID="txtPostal" runat="server"></asp:TextBox> </td> </tr> <tr> <td> <asp:Label ID="lblUrl" runat="server" Text="URL"></asp:Label> </td> <td> <asp:TextBox ID="txtUrl" runat="server"></asp:TextBox> </td> </tr> <tr> <td colspan="2" class="center"> <asp:CheckBox ID="chkAgree" runat="server" /> <asp:Label ID="lblAgree" runat="server" Text="I agree to the terms and conditions"></asp:Label> </td> </tr> <tr> <td colspan="2" class="center"> <asp:Button ID="btnSubmit" runat="server" Text="Submit" /> <asp:Button ID="btnReset" runat="server" Text="Reset" /> </td> </tr> </table> </form> -
在表单中添加以下样式:
.mandatory{ color:red; } .center{ text-align:center; } -
验证表单之后,验证插件使用 CSS 类
error在标签元素中生成错误消息。 要自定义错误消息的样式,我们可以添加我们自己的样式,如下所示: -
表单在顶部提供了一个
div元素来显示无效元素的总数。 让我们为这个元素添加以下样式:
怎么做……
将以下 jQuery 代码添加到窗体的<script>块中:
<script type="text/javascript">
$(document).ready(function() {
$("#summary").hide();
$("#<%=btnSubmit.ClientID%>").on("click", function() {
var validator = $("#frmRegistration").validate({
rules: {
<%=txtName.ClientID%>: "required",
<%=txtEmail.ClientID%>: {
required: true,
email: true
},
<%=txtPassword.ClientID%>: {
required: true,
minlength: 8
},
<%=txtConfirmPassword.ClientID%>: {
required: true,
minlength: 8,
equalTo: "#<%=txtPassword.ClientID%>"
},
<%=txtDOB.ClientID%>: {
date: true
},
<%=txtMailAddr.ClientID%>: {
maxlength: 200
},
<%=txtPostal.ClientID%>: {
digits: true
},
<%=txtUrl.ClientID%>: {
url: true
},
<%=chkAgree.ClientID%>: "required"
},
messages: {
<%=txtName.ClientID%>: "Please enter your Name",
<%=txtEmail.ClientID%>: {
required: "Please enter your Email",
email: "Please enter a valid Email address"
},
<%=txtPassword.ClientID%>: {
required: "Please enter your Password",
minlength: "Password should be at least 8 characters long"
},
<%=txtConfirmPassword.ClientID%>: {
required: "Please confirm your Password",
minlength: "Password should be at least 8 characters long",
equalTo: "Your entered passwords do not match"
},
<%=txtDOB.ClientID%>: "Enter a valid date",
<%=txtMailAddr.ClientID%>: "Your address exceeds 200 characters",
<%=txtPostal.ClientID%>: "Please enter only digits",
<%=txtUrl.ClientID%>: "Please enter a valid Url",
<%=chkAgree.ClientID%>: "Please accept the terms and conditions to proceed"
},
errorPlacement: function(error, element) {
if (element.prop("id") == "<%=chkAgree.ClientID%>") error.insertAfter(element.siblings("#<%=lblAgree.ClientID%>"));
else
error.insertAfter(element);
},
invalidHandler: function() {
$("#summary").html("Please correct the " + validator.numberOfInvalids() + " invalid field(s) on the form.").show();
}
});
});
$("#<%=btnReset.ClientID%>").on("click", function(evt) {
evt.preventDefault();
$("#summary").hide();
$("input[type=text]").val("");
$("input[type=password]").val("");
$("input[type=checkbox]").prop("checked", false);
$("#frmRegistration").validate().resetForm();
});
});
</script>
How it works…
验证插件工作原理如下:
-
On running the page in the browser, if the Submit button is clicked without entering any data into the fields, we will see that the following error messages are displayed for invalid fields along with a summary on the top:
![How it works…]()
-
When data is entered in the form, you will notice that the error messages will get updated to give you more specific details about the invalid fields, as shown in the following screenshot:
![How it works…]()
当您单击Reset按钮时,它将清除所有字段和错误消息。
-
To validate the fields, we call the
validate()method on the form when you click on the Submit button:$("#<%=btnSubmit.ClientID%>").on("click", function () { var validator = $("#frmRegistration").validate({…});validate()方法有许多选项。 我们将采用下列方案:-
规则:这由键/值对组成,用于验证表单上的控件。
-
消息:这由键/值对组成,用于定义自定义错误消息。
-
errorPlacement:执行一个函数,用于定制错误消息的位置。 函数的第一个实参是
error标签,作为jQuery对象提供,第二个实参是invalid元素,作为jQuery对象提供。 -
invalidHandler:当窗体被标记为无效时,执行一个
callback函数。var validator = $("#frmRegistration").validate({ rules: { }, messages: { }, errorPlacement: function(error, element) { }, invalidHandler: function() { } });
以上这些选项以以下方式应用于
validate()方法: -
-
rules 选项采用以下名称/值对来列出验证规则:
-
Name字段为必填字段:
<%=txtName.ClientID%>: "required", -
Email字段是必须的,并且应该有一个有效的
email:<%=txtEmail.ClientID%>: { required: true, email: true }, -
密码字段为强制输入,输入的密码长度至少为
8字符:<%=txtPassword.ClientID%>: { required: true, minlength: 8 } -
Confirm Password字段也是必须的,输入的密码长度至少为
8个字符。 更重要的是,输入的数据应该匹配Password字段:<%=txtConfirmPassword.ClientID%>: { required: true, minlength: 8 , equalTo: "#<%=txtPassword.ClientID%>"}, -
出生日期字段应该有一个有效的
date:<%=txtDOB.ClientID%>: { date: true }, -
邮件地址字段中输入的最大文本长度为
200字符:<%=txtMailAddr.ClientID%>: { maxlength: 200 }, -
邮政编码字段应该只有数字:
<%=txtPostal.ClientID%>: { digits: true }, -
URL字段应该有一个有效的 URL:
<%=txtUrl.ClientID%>: { url: true }, -
条款和条件应达成一致,即要求勾选复选框:
<%=chkAgree.ClientID%>:"required"
-
-
对于前面的规则,定义相应的错误消息。 这些错误消息将覆盖验证插件提供的默认错误消息:
-
Name字段:
<%=txtName.ClientID%>: "Please enter your Name", -
Email字段:
<%=txtEmail.ClientID%>: {required: "Please enter your Email", email: "Please enter a valid Email address"}, -
密码字段:
<%=txtPassword.ClientID%>: {required: "Please enter your Password", minlength:"Password should be at least 8 characters long"}, -
确认密码字段:
<%=txtConfirmPassword.ClientID%>: {required: "Please confirm your Password", minlength:"Password should be at least 8 characters long", equalTo: "Your entered passwords do not match" }, -
出生日期字段:
<%=txtDOB.ClientID%>: "Enter a valid date", -
邮寄地址字段:
<%=txtMailAddr.ClientID%>: "Your address exceeds 200 characters", -
邮政编码字段:
<%=txtPostal.ClientID%>: "Please enter only digits", -
URL字段:
<%=txtUrl.ClientID%>: "Please enter a valid Url", -
条款和条件复选框:
<%=chkAgree.ClientID%>:"Please accept the terms and conditions to proceed"
-
-
Each of the preceding error messages are displayed next to the respective invalid element. To override this default placement, we can attach a function to the
errorPlacementoption. Let's do this for the checkbox since we want to display the error message after the label I agree to the terms and conditions instead of next to the checkbox element. This can be done as follows:errorPlacement: function(error, element){ if (element.prop("id") == "<%=chkAgree.ClientID%>") error.insertAfter(element.siblings("#<%=lblAgree.ClientID%>")); else error.insertAfter(element); },因此,如果元素是
chkAgree,则将error标签插入到lblAgree元素之后。 -
Lastly, execute a callback function when the form is marked as invalid. This callback function will display the total number of invalid fields on the form:
invalidHandler: function () { $("#summary").html("Please correct the " + validator.numberOfInvalids() + " invalid field(s) on the form.").show(); }前面的错误消息显示在表单顶部的
summarydiv 中。 -
When you click on the Reset button, first of all the posting of the form is prevented:
evt.preventDefault();用来显示验证
summary的 div 被隐藏:$("#summary").hide();接下来,所有的表单字段被清空/重置:
$("input[type=text]").val(""); $("input[type=password]").val(""); $("input[type=checkbox]").prop("checked",false);resetForm()方法在validate()方法返回的验证器对象上调用,这样所有的验证都被重置:$("#frmRegistration").validate().resetForm();
还有更多的…
假设我们有一组想要一起验证的控件。 例如,电话字段可以输入一个手电话、工作电话或家庭电话,如下图所示:

如果我们需要以至少输入一个电话号码的方式验证这三个字段,那么使用验证插件提供的require_from_group方法。 该方法在发行版中可用的additional-methods.js文件中可用,可以从http://jqueryvalidation.org下载。
要验证 Phone 字段,请遵循以下步骤:
-
从http://jqueryvalidation.org下载
additional-methods.js文件,并将其包含在项目的Scripts文件夹中。 将此文件包含在以下表格中:<script src="Scripts/additional-methods.js"></script> -
在表单上添加 Phone 字段的标记:
<tr> <td> <asp:Label ID="lblPhone" runat="server" Text="Phone (provide at least one)"></asp:Label><span class="mandatory">*</span></td> <td> <table> <tr> <td> <asp:Label ID="lblHandphone" runat="server" Text="Hand Phone"></asp:Label> <asp:TextBox ID="txtHandphone" CssClass="phonegroup" runat="server"></asp:TextBox> </td> <td> <asp:Label ID="lblWorkphone" runat="server" Text="Work Phone"></asp:Label> <asp:TextBox ID="txtWorkphone" CssClass="phonegroup" runat="server"></asp:TextBox> </td> <td> <asp:Label ID="lblHomephone" runat="server" Text="Home Phone"></asp:Label> <asp:TextBox ID="txtHomephone" CssClass="phonegroup" runat="server"></asp:TextBox> </td> </tr> </table> </td> </tr> -
注意,组中的
TextBox控件被分配了相同的 CSS 类phonegroup。 -
In the
validate()method, add the following rules:<%=txtHandphone.ClientID%>: {require_from_group: [1, ".phonegroup"], phoneUS: true}, <%=txtWorkphone.ClientID%>: {require_from_group:[1, ".phonegroup"], phoneUS: true}, <%=txtHomephone.ClientID%>: {require_from_group:[1,".phonegroup"], phoneUS: true},require_from_group方法需要以下两个选项:- 选项 1:组中需要填写的字段个数
- 选项 2:CSS 组选择器
设置
phoneUs为true,表示该字段为电话字段。 -
添加相应的错误消息:
<%=txtHandphone.ClientID%>: {phoneUS: "Please enter a correct phone number"}, <%=txtWorkphone.ClientID%>: {phoneUS: "Please enter a correct phone number"}, <%=txtHomephone.ClientID%>:{phoneUS: "Please enter a correct phone number"}, -
To display a common message for all the three controls, we use the
groupsoption of thevalidate()method:groups: { phoneFields: "<%=String.Concat(txtHandphone.ClientID, " ")%><%=String.Concat(txtWorkphone.ClientID, " ")%><%=txtHomephone.ClientID%>" },在前面的代码片段中,我们为组分配了一个任意名称,即
phoneFields。 分配给该字段的值是组中以空格分隔的控件列表。 在运行时,phoneFields将被计算为以下字符串:phoneFields: "txtHandphone txtWorkphone txtHomephone" -
为了在适当的位置显示此组的错误,还更新了
errorPlacement选项。 在这里,error标签被附加到父容器表: -
Thus, on validation, a common error message is displayed for the three controls:
![There's more…]()
-
On entering incorrect data into any of the phone fields, the error message will change to the following:
![There's more…]()
参见 also
使用 NPM 配方下载插件
使用 NPM 下载插件
由于 jQuery 插件库现在处于只读模式,建议使用NPM(Node Package Manager)管理插件。 在本教程中,我们将使用 NPM 和 Bower 下载 jQuery 验证插件。
注意事项
Bower 是一个浏览器包管理器。 它被优化用于管理前端包。 然而,为了使用 Bower,你需要安装Node.js和NPM。 一些 bower 包也需要Git来安装。
准备
Bower 可以设置如下:
-
The first step is to install Node.js and NPM on your machine. Node.js is available at https://nodejs.org. On the home page, click on the Download link to download the required version:
![Getting ready]()
-
安装完成后,在终端窗口(例如 Windows 机器上的 cmd)中使用以下命令进行测试:
node –v npm -v -
接下来,从http://git-scm.com下载 Git 安装程序。 运行并完成安装。
-
接下来,将 Bower 安装为一个全局节点模块。 为此,打开终端窗口并输入以下命令:
npm install –g bower
怎么做……
现在已经安装好了所有需要的软件,可以使用 Bower 安装 jQuery 验证插件,在终端窗口中输入如下命令:
bower install jquery-validation
终端窗口将显示以下安装消息:

How it works…
-
Bower 在机器上创建了一个
bower_components文件夹,并在此文件夹中下载插件及其依赖项,即 jQuery 库。 -
After going to the
jquery-validationfolder, we can see the downloaded files:![How it works…]()
-
The validation plugin files can be found in the distribution folder, that is,
bower_components/jquery-validation/dist, as shown in the following screenshot:![How it works…]()
参见 also
使用表单验证n 插件配方***





















































































































































































































浙公网安备 33010602011771号