jQuery 库位于一个 JavaScript 文件中,其中包含了所有的 jQuery 函数
<head> <script type="text/javascript" src="jquery.js"></script> </head> <!----注意:位于head标记里--->
jQuery事件 --ready()
当 DOM(文档对象模型) 已经加载后执行,与onload对比
1.执行时间
window.onload必须等到页面内包括图片的所有元素加载完毕后才能执行。
$(document).ready()是DOM结构绘制完毕后就执行,不必等到加载完毕。
2.编写个数不同
window.onload不能同时编写多个,如果有多个window.onload方法,只会执行一个
$(document).ready()可以同时编写多个,并且都可以得到执行
<!--ready方法的2种常用写法:--> 1.$(document).ready(function(){ alert("hello word"); }); 2.$(function(){ });
$符号是定义jQuery,所以$ or jQuery 都是一样的
jQuery还可以从Google或Microsoft加载CDN JQuery核心文件,使用Google或者微软的jQuery有个很大的优势,那就是许多用户访问其他站点时以及自动加载了jQuery,当他们访问你的站点时,会调用缓存的jQuery。提高加载速度。
使用 Google 的 CDN <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs /jquery/1.4.0/jquery.min.js"></script> </head>
使用 Microsoft 的 CDN <head> <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery /jquery-1.4.min.js"></script> </head>
jQuery元素选择器 $(this).hide() 隐藏当前html元素。 $(".a").hide() 隐藏所有class = a 的元素 $("#a").hide() 隐藏id = a 的元素 $("p").hide() 隐藏所有p标签 $("p.intro") 选取class = intro的p标签
jQuery 属性选择器 $("[href]") 选取所有带有href的元素 $("[href='#']") 选取所有href等于#的元素 $("[href!='#']") 选取所有href不等于#的元素 $("[href$='.jsp']")选取所有href值以.jsp结尾的元素 $("ul li:first") 选取所有ul中的第一个li $("div#a.a")选取id=a并且class=a的div jQuery CSS 选择器 $("p").css("background-color","red"); 将所有p标签的背景色改为red
jQuery显示、隐藏对象
<script type="text/javascript"> $(document).ready(function(){ $(".btn1").click(function(){ /*当按钮.btn1被点击时执行下面代码、匿名函数*/ $("p").toToggle(); /*显示或隐藏,显示show() 隐藏hide(),每个方法都会带有2个参数,一个是速度(slow,fast,毫秒),一个是执行之后执行的函数名*/ }); }); </script> <p>This is a paragraph.</p> <button class="btn1">Toggle</button>
query 淡入、淡出对象
$(selector).fadeIn(speed,callback);
例子:
<script> $(document).ready(function(){ $("#dd").click(function(){ $("#s").fadeIn("slow"); $("#a").fadeIn("fast"); }) $("#cc").click(function(){ $("#s").fadeOut("slow"); $("#a").fadeOut("fast"); }) $("#as").click(function(){ $("#s").fadeToggle("slow"); $("#a").fadeToggle("fast"); }) }) </script> <body> <button id="dd">点我淡入</button> <button id="cc">点我淡出</button> <button id="as">点我淡出或淡入</button> <div id="s"></div> <div id="a"></div> </body>