jQuery入门

第一种根据表达式(ID,DOM元素名,CSS表达式,XPath表达式)找出文档中的元素,并组装成一个jQuery对象返回。
DEMO:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    
<title>jQuery basic</title>
    
<style type="text/css">
         .selected
        
{
             background-color
:Yellow;
        
}
    
</style>
    
<script src="../scripts/jquery-1.2.3.intellisense.js" type="text/javascript"></script>
</head>
<body>
    
<h3>jQuery构造函数</h3>
    
<ul>
        
<li>jQuery(expression,context)</li>
        
<li>jQuery(html)</li>
        
<li>jQuery(elements)</li>
        
<li>jQuery(fn)</li>
    
</ul>
    
<script type="text/javascript">
    
</script>
</body>
</html>


将以下jQuery代码加入文末的脚本块中:

jQuery("ul>li:first").addClass("selected");

页面运行效果如下:

其中jQuery()可替换为快捷方式$(),如果$被其它对象占用,可使用jQuery.noConflict()函数取消快捷方式。
"ul>li:first"中ul>li表示所有位于ul下的li元素(为CSS表达式,XPath方式可用ul/li),:first表示其中的第一个。addClass()为jQuery对象用来添加CSS样式类的函数,相反的函数为removeClass()。
再加入以下代码:

$('ul').append($('<li>new item</li>'));

运行效果如下:

其中$('<li>new item</li>')将其中的字符串转换为DOM对象,然后通过append()函数加入ul对象的最后。
接下来:

         $(document).ready(function(){
             $(
'ul').css('color','red');
         });

则效果如:

jQuery构造函数中还可以真接传入DOM对象,如document,或jQuery对象(当然就没什么意义)。ready()函数为document添加事件处理函数,将ul的颜色设为红色。
$(document).ready()由于应用场景众多,所以可以直接用$(fn)来代替,fn表示处理函数。(ready处理函数貌似在文档内容载入完成后执行,无需等待相关其它图片等资源载入完成,所以比load事件要更早执行,对于这点,没有具体证实)

         $(function(){
             alert(
'welcome to jQuery');
         });

以上代码的效果是页面一载入,就弹出一个对话框。

reference:
http://docs.jquery.com/Core
http://docs.jquery.com/Core和http://docs.jquery.com/Selectors
jQuery之所以令人爱不释手,在于其强大的选择器表达式令DOM操作优雅而艺术。
jQuery的选择符支持id,tagName,css1-3 expressions,XPath,参见:http://docs.jquery.com/Selectors
DEMO:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    
<title>Selector</title>
    
<script src="../scripts/jquery-1.2.3.intellisense.js" type="text/javascript"></script>
</head>
<body>
    
<input value="1"/> +
    
<input value="2"/>
    
<input type="button" value="="/>
    
<label>&nbsp;</label>
    
<script type="text/javascript">
         $(
"input[type='button']").click(function(){
            
var i =0;
             $(
"input[type='text']").each(function(){
                 i
+= parseInt($(this).val());
             });
             $(
'label').text(i);
         });
         $(
'input:lt(2)')
             .add(
'label')
             .css(
'border','none')
             .css(
'borderBottom','solid 1px navy')
             .css({
'width':'30px'});
    
</script>
</body>
</html>



代码分解:
$("input[type='button']")用于找到type属性为button的input元素(此为CSS表达式,IE7才开始支持,所以在IE6中通常用jQuery的这种表达式代替CSS代码设置样式)。click()函数为button添加click事件处理函数。
在button_click时,$("input[type='text']")找出所有输入框,each()函数遍历找出来的数组中的对象的值,相加后设到label中。
        $('input:lt(2)')
            .add('label')
两行代码意为:所有input中的前面两个(lt表示序号小于)再加上label对象合并成一个jQuery对象。
            .css('border','none')
            .css('borderBottom','solid 1px navy')
            .css({'width':'30px'});
以上三行代码都是针对之前的jQuery对象设置CSS样式,如果一次需要设置多个CSS值,可用另一种形式,如:
            .css({'border':'none','borderBottom':'solid 1px navy','width':'30px'});
css()函数如果只传一个字符串参数,则为取样式值,比如css('color')为取得当前jQuery对象的样式属性color的值。jQuery对象有多种这样的函数,比如,val('')为设value,val()为取value,text('text')为设innerText,text()为取得innerText,此外还有html(),用于操作innerHTML,而click(fn)/click(),change(fn)/change()……系统函数则为事件的设置处理函数与触发事件。
由于多数jQuery对象的方法仍返回当前jQuery,所以jQuery代码通常写成一串串的,如上面的
            .css('border','none')
            .css('borderBottom','solid 1px navy')
            .css({'width':'30px'});
,而不需要不断重复定位对象,这是jQuery的链式特点,后面文章还会有补充。

referrence:http://docs.jquery.com/Selectors
jQuery对事件的支持主要包括:

  • bind()--为事件绑定处理程序,如:
    $("p").bind("mouseenter mouseleave", function(e){

    $(this).toggleClass("over");

    });
  • unbind()--注销绑定在事件上的处理程序,如:$(document).unbind('ready');,如不给参数,则清除所有事件处理程序。
    $("#unbind").click(function () {

    $("#theone").unbind('click', aClick);

    });
  • trigger()--触发某类事件。
    $("button:first").trigger('click');
  • triggerHandler()--触发某类事件,但不触发默认的事件处理逻辑,比如a的定向。
    $("input").triggerHandler("focus");
  • one()--为事件绑定只能被触发一次的处理程序。
    $("div").one("click", function(){

    });
  • ready()/click()/change()/toggle(fn,fn)/dblclick()……各种常规事件的快捷方式,xxx(fn)为绑定处理程序,xxx()为触发事件


jQuery 1.2的事件支持命名空间,

$("div").bind("click", function(){ alert("hello"); });

$("div").bind("click.plugin", function(){ alert("goodbye"); });

$("div").trigger("click!"); // alert("hello") only



DEMO:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    
<title>Events</title>
    
<script src="../scripts/jquery-1.2.3.intellisense.js" type="text/javascript"></script>
    
<style type="text/css">
         textarea
        
{
             height
: 118px;
             width
: 280px;
        
}
    
</style>
    
<script type="text/javascript">
         $(
function(){
             $(
'textarea').bind('propertychange',function(){
                 $(
'#result').html($('textarea').val())
             }
             ).bind(
'change',function(){
                 alert($(
'textarea').val());
             });
         });
    
    
</script>
</head>
<body>
    
<textarea></textarea>
    
<div id='result'></div>
</body>
</html>
Reference:http://docs.jquery.com/Events

jQuery另一个很令人惬意的地方是,一般的代码都是一行一行写,jQuery的代码可以一串一串写。
这一点,在前面的文章中已经介绍过了。
直接来一个Demo:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    
<title>chainning code</title>
    
<script src="../scripts/jquery-1.2.3.intellisense.js" type="text/javascript"></script>
    
<script type="text/javascript">
         $(
function(){
            
//添加四个按钮
             $('<input type="button" value="click me"/><input type="button" value="triggle click me"/><input type="button" value="detach handler"/><input type="button" value="show/hide text"/>').appendTo($('body'));
            
//找出所有按钮
             $('input[type="button"]')
                 .eq(
0)//找到第一个按钮
                     .click(function(){
                         alert(
'you clicked me!');
                     })
                 .end().eq(
1)//返回所有按钮,再找到第二个
                     .click(function(){
                         $(
'input[type="button"]:eq(0)').trigger('click');
                     })
                 .end().eq(
2)//返回所有按钮,再找到第三个
                     .click(function(){
                         $(
'input[type="button"]:eq(0)').unbind('click');
                     })
                 .end().eq(
3)//返回所有按钮,再找到第四个
                     .toggle(function(){
                         $(
'.panel').hide('slow');
                     },
function(){
                         $(
'.panel').show('slow');
                     });
         });
    
</script>
    
<style type="text/css">
         .panel
        
{
             padding
: 20px;
             background-color
: #000066;
             color
: #FFFFFF;
             font-weight
: bold;
             width
: 200px;
             height
: 50px;
        
}
    
</style>
</head>
<body>
    
<div class="panel">welcome to jQuery!</div>
</body>
</html>



现在,链式代码已经成为jQuery非常流行的一个特点了,在使用链条方式写代码时,可能会用到eq()/filter()……(reference:http://docs.jquery.com/Traversing)等方法变化jQuery对象的对应范围,然后,又可以用end()函数将范围复原到原来的状况。
需要注意的是,有几个函数并不返回jQuery对象,所以链条就不能继续下去,比如get()就不能像eq()那样用。

jQuery为AJAX提供了非常丰富的支持,参见Ajax
其中最基本当属$ajax(),通过不同的参数,这个方法可以录活支持各种AJAX应用场景。如:
$.ajax({

url: "test.html",

cache: false,

success: function(html){

$("#results").append(html);

}

});

完整参数列表参见:options

当然,常用的应该是这些:
  • load()--直接将AJAX请求结果作为jQuery对象内容
  • $.get()--用get方式请求
  • $.post()--用post方式提交
  • ajaxStart()/ajaxComplete()/ajaxError()……--全局的ajax事件响应

DEMO:
建一个GenericHandler作AJAX请求服务端:CubeHandler.ashx
<%@ WebHandler Language="C#" Class="CubeHandler"%>

using System;
using System.Web;

publicclass CubeHandler : IHttpHandler {
    
    
publicvoid ProcessRequest (HttpContext context) {
         context.Response.ContentType
="text/plain";
        
int number =0;
        
int.TryParse(context.Request.Params["number"], out number);
         context.Response.StatusCode
=200;
         context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
         context.Response.Write(
string.Format("{0} cubed is {1}",number,Math.Pow(number, 3)));
     }

    
publicbool IsReusable {
        
get {
            
returntrue;
         }
     }
}
因为用的是Request.Params,所以这个handler能同时支持get和post,
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    
<title>ajax</title>
    
<script src="../scripts/jquery-1.2.3.intellisense.js" type="text/javascript"></script>
    
<script type="text/javascript">
         $(
function(){
            
//设置指示器
             $('#divIndicator').ajaxStart(function(){$(this).show()})
                             .ajaxSuccess(
function(){$(this).hide()})
                             .ajaxError(
function(msg){$(this).hide();alert(msg);});
            
//ajax get 请求
             $('#btnGetCubeInGet').click(function(){
                
var number = $('#txtNumber').val();
                 $.get(
'CubeHandler.ashx?number='+number,function(result){
                     alert(result);
                 });
             });
            
            
//ajax post 提交
             $('#btnGetCubeInPost').click(function(){
                
var number = $('#txtNumber').val();
                 $.get(
'CubeHandler.ashx',{'number':number},function(result){
                     alert(result);
                 });
             });
         });
    
</script>
    
<style type="text/css">
         .indicator
        
{
             color
: #FF0000;
             position
: absolute;
             top
: 0px;
             right
: 0px;
             display
: none;
        
}
    
</style>
</head>
<body>
    
<div id="divIndicator" class="indicator">
        
<img src="indicator.gif"/>loading</div>
     plz input a number:
<input id="txtNumber"/>
    
<input type="button" id="btnGetCubeInGet" value="Get cube(get)"/>
    
<input type="button" id="btnGetCubeInPost" value="Get cube(post)"/>
</body>
</html>
Query直接各种动画,常见的被封装成各种方法,如show()/hide()/slideDown()/fadeIn()等等,参见:Effects

最灵活的则属于animate( params, [duration], [easing], [callback] )方法,参见:animate
其中params为动画的运行结果,可以为各种样式属性,jQuery将在duration指定的时间内,将对象的当前状态渐变为params参数指定的值。如:
     $("#go").click(function(){
       $(
"#block").animate({
        
"70%",
         opacity:
0.4,
         marginLeft:
"0.6in",
         fontSize:
"3em",
         borderWidth:
"10px"
       },
1500 );
     });

params也可以是一些相对数据:
     $("#right").click(function(){
       $(
".block").animate({"left": "+=50px"}, "slow");
     });

     $(
"#left").click(function(){
       $(
".block").animate({"left": "-=50px"}, "slow");
     });

通过stop()函数可将对象再在执行的动画暂停。选择符:animated可以判断对象是否处在动画运行状态。
以下为来自官网的一个例子:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                     "http://www.w3.org/TR/html4/loose.dtd"
>
<html>
<head>
  
<script src="http://code.jquery.com/jquery-latest.js"></script>
  
  
<script>
   $(document).ready(
function(){
    
     $(
"#show").click(function () {
      
var n = $("div").queue("fx");
       $(
"span").text("Queue length is: "+ n.length);
     });
    
function runIt() {
       $(
"div").show("slow");
       $(
"div").animate({left:'+=200'},2000);
       $(
"div").slideToggle(1000);
       $(
"div").slideToggle("fast");
       $(
"div").animate({left:'-=200'},1500);
       $(
"div").hide("slow");
       $(
"div").show(1200);
       $(
"div").slideUp("normal", runIt);
     }
     runIt();

   });
  
</script>
  
<style>
   div
{ margin:3px; width:40px; height:40px;
         position
:absolute; left:0px; top:30px;
         background
:green; display:none;}
   div.newcolor
{ background:blue;}
   span
{ color:red;}
  
</style>
</head>
<body>
  
<button id="show">Show Length of Queue</button>
  
<span></span>
  
<div></div>
</body>
</html>
效果为不断变化的一个方块,因为最后一个动画$("div").slideUp("normal", runIt)执行后又 调用runIt方法,所以动画不断循环。



原文地址:https://www.cnblogs.com/jcomet/p/1242805.html