JQuery介绍

1. jQuery库

      ASP.NET MVC模板会自动地包含JQuery文件,并把它们放置在Scripts文件夹中以方便程序员使用,如下表所示。

文件名 描述
jquery-1.7.1.intellisense.js 支持核心库和验证模型库的智能感知功能的库文件
jquery.validate-vsdoc.js
jquery-1.7.1.js 常规的和最小化的jquery核心库文件
jquery-1.7.1.min.js
jquery-ui-1.8.20.js 常规的和最小化的jquery UI文件
jquery-ui-1.8.20.min.js
jquery.unobtrusive-ajax.js 常规的和最小化的非侵入的Ajax库文件
jquery.unobtrusive-ajax.min.js
jquery.validate.js 常规的和最小化的客户端验证模型库文件
jquery.validate.min.js
jquery.validate.unobtrusive.js 常规的和最小化的非侵入的客户端验证模型库文件
jquery.validate.unobtrusive.min.js

      VS的智能感知(IntelliSense)功能可以帮助程序员快捷地使用jQuery库,只需要在页面代码中增加引用jquery-1.7.1.intellisense.js文件的代码即可。例如:

...
<head>
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
    @if(false){
    <script src="../../Scripts/jquery-1.7.1.inellisense.js" type="text/javascript"></script>
    }
</head>
...

     上面的代码中增加了Razor引擎的if语句以阻止客户端的浏览器下载jquery-1.7.1.intellisense.js文件,因为该文件只包含了对Visual Studio有用的信息,客户端程序不需要使用该文件。一旦增加了jquery-1.7.1.intellisense.js文件,那么在编写jQuery代码时,就会出现智能感知现象。

2. jQuery语法基础

      jQuery语法是为了HTML元素的选取编制的,可以对元素执行某些操作。

      基础语法是:$(selector).action()。其中:$定义jQuery; selector查询和查找HTML元素; action()执行对元素的操作。

      例如:

      $(this).hide();  //隐藏当前元素

      $("p").hide();  //隐藏所有段落

      $("p.test").hide();  //隐藏所有class="test"的段落

      $("#test").hide();  //隐藏所有id="test"的元素

3. jQuery初步使用

(1)给元素附加class

      例如,找出一个页面的所有<div />元素,并为每个元素添加CSS的class,即所有<div />元素称为<div class="foo" />

$('div').addClass('foo');

(2)给元素附加事件

      例如,想在点击按钮时显示一个消息框。

      传统做法如下。代码与标记混合在一起,可能会影响应用程序的可维护性,并使其逻辑难以跟踪。

<button id="myButton" onclick="alert('I was clicked!’)">
    Click me!
</button>

      通过使用jQuery,可以对按钮的点击事件附件一个外部事件处理程序。

<button id="myButton">
    Click me!
</button>
<script type="text/javascript">
    $('button#myButton').click(function(){
        alert('I was clicked!');
     });
</script>

     最好将所有事件绑定和jQuery代码都包含到ready处理程序之中:

$(document).ready(function()
{ 
    $('button#myButton').click(function()
    {
        alert('I was clicked!');
     });
});

 

posted @ 2014-11-20 13:46  liesl  阅读(767)  评论(0编辑  收藏  举报