一、简介
1.1、概述
随着WEB2.0及ajax思想在互联网上的快速发展传播,陆续出现了一些优秀的Js框架,其中比较著名的有Prototype、YUI、jQuery、
mootools、Bindows以及国内的JSVM框架等,通过将这些JS框架应用到我们的项目中能够使程序员从设计和书写繁杂的JS应用中解脱
出来,将关注点转向功能需求而非实现细节上,从而提高项目的开发速度。
jQuery是继prototype之后的又一个优秀的Javascript框架。它是由 John Resig 于 2006 年初创建的,它有助于简化 JavaScript?
以及Ajax 编程。有人使用这样的一比喻来比较prototype和jQuery:prototype就像Java,而jQuery就像ruby. 它是一个简洁快速灵
活的JavaScript框架,它能让你在你的网页上简单的操作文档、处理事件、实现特效并为Web页面添加Ajax交互。
它具有如下一些特点:
代码简练、语义易懂、学习快速、文档丰富。
jQuery是一个轻量级的脚本,其代码非常小巧,最新版的JavaScript包只有20K左右。
jQuery支持CSS1-CSS3,以及基本的xPath。
jQuery是跨浏览器的,它支持的浏览器包括IE 6.0+, FF 1.5+, Safari 2.0+, Opera 9.0+。
可以很容易的为jQuery扩展其他功能。
能将JS代码和HTML代码完全分离,便于代码和维护和修改。
插件丰富,除了jQuery本身带有的一些特效外,可以通过插件实现更多功能,如表单验证、tab导航、拖放效果、表格排序、
DataGrid,树形菜单、图像特效以及ajax上传等。
jQuery的设计会改变你写JavaScript代码的方式,降低你学习使用JS操作网页的复杂度,提高网页JS开发效率,无论对于js初学者
还是资深专家,jQuery都将是您的首选。
jQuery适合于设计师、开发者以及那些还好者,同样适合用于商业开发,可以说jQuery适合任何JavaScript应用的地方,可用于不
同的Web应用程序中。
官方站点:http://jquery.com/ 中文站点:http://jquery.org.cn/
1.2、目的
通过学习本文档,能够对jQuery有一个简单的认识了解,清楚JQuery与其他JS框架的不同,掌握jQuery的常用语法、使用技巧及注
意事项。
二、使用方法
在需要使用JQuery的页面中引入JQuery的js文件即可。
例如:<script type="text/javascript" src="js/jquery.js"></script>
引入之后便可在页面的任意地方使用jQuery提供的语法。
三、学习教程及参考资料
请参照《jQuery中文API手册》和http://jquery.org.cn/visual/cn/index.xml
推荐两篇不错的jquery教程:《jQuery的起点教程》和《使用 jQuery 简化 Ajax 开发》
文章由jquery分享网站整理
<!--------------------------------------------------------------------------->
四、语法总结和注意事项
1、关于页面元素的引用
通过jquery的$()引用元素包括通过id、class、元素名以及元素的层级关系及dom或者xpath条件等方法,且返回的对象为jquery对
象(集合对象),不能直接调用dom定义的方法。
2、jQuery对象与dom对象的转换
只有jquery对象才能使用jquery定义的方法。注意dom对象和jquery对象是有区别的,调用方法时要注意操作的是dom对象还是
jquery对象。
普通的dom对象一般可以通过$()转换成jquery对象。
如:$(document.getElementById("msg"))则为jquery对象,可以使用jquery的方法。
由于jquery对象本身是一个集合。所以如果jquery对象要转换为dom对象则必须取出其中的某一项,一般可通过索引取出。
如:$("#msg")[0],$("div").eq(1)[0],$("div").get()[1],$("td")[5]这些都是dom对象,可以使用dom中的方法,但不能再使
用Jquery的方法。
以下几种写法都是正确的:
$("#msg").html();
$("#msg")[0].innerHTML;
$("#msg").eq(0)[0].innerHTML;
$("#msg").get(0).innerHTML;
3、如何获取jQuery集合的某一项
对于获取的元素集合,获取其中的某一项(通过索引指定)可以使用eq或get(n)方法或者索引号获取,要注意,eq返回的是jquery
对象,而get(n)和索引返回的是dom元素对象。对于jquery对象只能使用jquery的方法,而dom对象只能使用dom的方法,如要获取第
三个<div>元素的内容。有如下两种方法:
$("div").eq(2).html(); //调用jquery对象的方法
$("div").get(2).innerHTML; //调用dom的方法属性
4、同一函数实现set和get
Jquery中的很多方法都是如此,主要包括如下几个:
$("#msg").html(); //返回id为msg的元素节点的html内容。
$("#msg").html("<b>new content</b>");
//将“<b>new content</b>” 作为html串写入id为msg的元素节点内容中,页面显示粗体的new content
$("#msg").text(); //返回id为msg的元素节点的文本内容。
$("#msg").text("<b>new content</b>");
//将“<b>new content</b>” 作为普通文本串写入id为msg的元素节点内容中,页面显示<b>new content</b>
$("#msg").height(); //返回id为msg的元素的高度
$("#msg").height("300"); //将id为msg的元素的高度设为300
$("#msg").width(); //返回id为msg的元素的宽度
$("#msg").width("300"); //将id为msg的元素的宽度设为300
$("input").val("); //返回表单输入框的value值
$("input").val("test"); //将表单输入框的value值设为test
$("#msg").click(); //触发id为msg的元素的单击事件
$("#msg").click(fn); //为id为msg的元素单击事件添加函数
同样blur,focus,select,submit事件都可以有这两种调用方法
文章由jquery分享网站整理
<!--------------------------------------------------------------------------->
5、集合处理功能
对于jquery返回的集合内容无需我们自己循环遍历并对每个对象分别做处理,jquery已经为我们提供的很方便的方法进行集合的处
理。
包括两种形式:
$("p").each(function(i){this.style.color=['#f00','#0f0','#00f'][i]})
//为索引分别为0,1,2的p元素分别设定不同的字体颜色。
$("tr").each(function(i){this.style.backgroundColor=['#ccc','#fff'][i%2]})
//实现表格的隔行换色效果
$("p").click(function(){alert($(this).html())})
//为每个p元素增加了click事件,单击某个p元素则弹出其内容
6、扩展我们需要的功能
$.extend({
min: function(a, b){return a < b?a:b; },
max: function(a, b){return a > b?a:b; }
}); //为jquery扩展了min,max两个方法
使用扩展的方法(通过“$.方法名”调用):
alert("a=10,b=20,max="+$.max(10,20)+",min="+$.min(10,20));
7、支持方法的连写
所谓连写,即可以对一个jquery对象连续调用各种不同的方法。
例如:
$("p").click(function(){alert($(this).html())})
.mouseover(function(){alert('mouse over event')})
.each(function(i){this.style.color=['#f00','#0f0','#00f'][i]});
8、操作元素的样式
主要包括以下几种方式:
$("#msg").css("background"); //返回元素的背景颜色
$("#msg").css("background","#ccc") //设定元素背景为灰色
$("#msg").height(300); $("#msg").width("200"); //设定宽高
$("#msg").css({ color: "red", background: "blue" });//以名值对的形式设定样式
$("#msg").addClass("select"); //为元素增加名称为select的class
$("#msg").removeClass("select"); //删除元素名称为select的class
$("#msg").toggleClass("select"); //如果存在(不存在)就删除(添加)名称为select的class
文章由jquery分享网站整理
<!--------------------------------------------------------------------------->
9、完善的事件处理功能
Jquery已经为我们提供了各种事件处理方法,我们无需在html元素上直接写事件,而可以直接为通过jquery获取的对象添加事
件。
如:
$("#msg").click(function(){alert("good")}) //为元素添加了单击事件
$("p").click(function(i){this.style.color=['#f00','#0f0','#00f'][i]})
//为三个不同的p元素单击事件分别设定不同的处理
jQuery中几个自定义的事件:
(1)hover(fn1,fn2):一个模仿悬停事件(鼠标移动到一个对象上面及移出这个对象)的方法。当鼠标移动到一个匹配的元素上面
时,会触发指定的第一个函数。当鼠标移出这个元素时,会触发指定的第二个函数。
//当鼠标放在表格的某行上时将class置为over,离开时置为out。
$("tr").hover(function(){
$(this).addClass("over");
},
function(){
$(this).addClass("out");
});
(2)ready(fn):当DOM载入就绪可以查询及操纵时绑定一个要执行的函数。
$(document).ready(function(){alert("Load Success")})
//页面加载完毕提示“Load Success”,相当于onload事件。与$(fn)等价
(3)toggle(evenFn,oddFn): 每次点击时切换要调用的函数。如果点击了一个匹配的元素,则触发指定的第一个函数,当再次点击
同一元素时,则触发指定的第二个函数。随后的每次点击都重复对这两个函数的轮番调用。
//每次点击时轮换添加和删除名为selected的class。
$("p").toggle(function(){
$(this).addClass("selected");
},function(){
$(this).removeClass("selected");
});
(4)trigger(eventtype): 在每一个匹配的元素上触发某类事件。
例如:
$("p").trigger("click"); //触发所有p元素的click事件
(5)bind(eventtype,fn),unbind(eventtype): 事件的绑定与反绑定
从每一个匹配的元素中(添加)删除绑定的事件。
例如:
$("p").bind("click", function(){alert($(this).text());}); //为每个p元素添加单击事件
$("p").unbind(); //删除所有p元素上的所有事件
$("p").unbind("click") //删除所有p元素上的单击事件
10、几个实用特效功能
其中toggle()和slidetoggle()方法提供了状态切换功能。
如toggle()方法包括了hide()和show()方法。
slideToggle()方法包括了slideDown()和slideUp方法。
文章由jquery分享网站整理
<!--------------------------------------------------------------------------->
11、几个有用的jQuery方法
$.browser.浏览器类型:检测浏览器类型。有效参数:safari, opera, msie, mozilla。如检测是否ie:$.browser.isie,是ie浏
览器则返回true。
$.each(obj, fn):通用的迭代函数。可用于近似地迭代对象和数组(代替循环)。
如
$.each( [0,1,2], function(i, n){ alert( "Item #" + i + ": " + n ); });
等价于:
var tempArr=[0,1,2];
for(var i=0;i<tempArr.length;i++){
alert("Item #"+i+": "+tempArr[i]);
}
也可以处理json数据,如
$.each( { name: "John", lang: "JS" }, function(i, n){ alert( "Name: " + i + ", Value: " + n ); });
结果为:
Name:name, Value:John
Name:lang, Value:JS
$.extend(target,prop1,propN):用一个或多个其他对象来扩展一个对象,返回这个被扩展的对象。这是jquery实现的继承方式。
如:
$.extend(settings, options);
//合并settings和options,并将合并结果返回settings中,相当于options继承setting并将继承结果保存在setting中。
var settings = $.extend({}, defaults, options);
//合并defaults和options,并将合并结果返回到setting中而不覆盖default内容。
可以有多个参数(合并多项并返回)
$.map(array, fn):数组映射。把一个数组中的项目(处理转换后)保存到到另一个新数组中,并返回生成的新数组。
如:
var tempArr=$.map( [0,1,2], function(i){ return i + 4; });
tempArr内容为:[4,5,6]
var tempArr=$.map( [0,1,2], function(i){ return i > 0 ? i + 1 : null; });
tempArr内容为:[2,3]
$.merge(arr1,arr2):合并两个数组并删除其中重复的项目。
如:$.merge( [0,1,2], [2,3,4] ) //返回[0,1,2,3,4]
$.trim(str):删除字符串两端的空白字符。
如:$.trim(" hello, how are you? "); //返回"hello,how are you? "
12、解决自定义方法或其他类库与jQuery的冲突
很多时候我们自己定义了$(id)方法来获取一个元素,或者其他的一些js类库如prototype也都定义了$方法,如果同时把这些内
容放在一起就会引起变量方法定义冲突,Jquery对此专门提供了方法用于解决此问题。
使用jquery中的jQuery.noConflict();方法即可把变量$的控制权让渡给第一个实现它的那个库或之前自定义的$方法。之后应
用Jquery的时候只要将所有的$换成jQuery即可,如原来引用对象方法$("#msg")改为jQuery("#msg")。
如:
jQuery.noConflict();
// 开始使用jQuery
jQuery("div p").hide();
// 使用其他库的 $()
$("content").style.display = 'none';
文章由jquery分享网站整理
<!--------------------------------------------------------------------------->
1. 禁用右键点击(Disable right-click)
$(document).ready(function(){
$(document).bind("contextmenu",function(e){
return false;
});
});
2. 禁用搜索文本框(Disappearing search field text)
$(document).ready(function() {
$("input.text1").val("Enter your search text here");
textFill($('input.text1'));
});
function textFill(input){ //input focus text function
var originalvalue = input.val();
input.focus( function(){
if( $.trim(input.val()) == originalvalue ){ input.val(''); }
});
input.blur( function(){
if( $.trim(input.val()) == '' ){ input.val(originalvalue); }
});
}
3. 新窗口打开链接(Opening links in a new window)
$(document).ready(function() {
//Example 1: Every link will open in a new window
$('a[href^="http://"]').attr("target", "_blank");
//Example 2: Links with the rel="external" attribute will only open in a new window
$('a[@rel$='external']').click(function(){
this.target = "_blank";
});
});
// how to use
<a href="http://www.opensourcehunter.com" rel="external">open link</a>
4. 检测浏览器(Detect browser)
$(document).ready(function() {
// Target Firefox 2 and above
if ($.browser.mozilla && $.browser.version >= "1.8" ){
// do something
}
// Target Safari
if( $.browser.safari ){
// do something
}
// Target Chrome
if( $.browser.chrome){
// do something
}
// Target Camino
if( $.browser.camino){
// do something
}
// Target Opera
if( $.browser.opera){
// do something
}
// Target IE6 and below
if ($.browser.msie && $.browser.version <= 6 ){
// do something
}
// Target anything above IE6
if ($.browser.msie && $.browser.version > 6){
// do something
}
});
文章由jquery分享网站整理
<!--------------------------------------------------------------------------->
5. 预加载图片(Preloading images)
$(document).ready(function() {
jQuery.preloadImages = function()
{
for(var i = 0; i<arguments.length; i++)="" {="" jquery("<img="">").attr("src", arguments[i]);
}
}
// how to use
$.preloadImages("image1.jpg");
});
</arguments.length;>
6. 样式筛选(CSS Style switcher)
$(document).ready(function() {
$("a.Styleswitcher").click(function() {
//swicth the LINK REL attribute with the value in A REL attribute
$('link[rel=stylesheet]').attr('href' , $(this).attr('rel'));
});
// how to use
// place this in your header
<link rel="stylesheet" href="default.css" type="text/css">
// the links
<a href="#" class="Styleswitcher" rel="default.css">Default Theme</a>
<a href="#" class="Styleswitcher" rel="red.css">Red Theme</a>
<a href="#" class="Styleswitcher" rel="blue.css">Blue Theme</a>
});
7. 列高度相同(Columns of equal height)
$(document).ready(function() {
function equalHeight(group) {
tallest = 0;
group.each(function() {
thisHeight = $(this).height();
if(thisHeight > tallest) {
tallest = thisHeight;
}
});
group.height(tallest);
}
// how to use
$(document).ready(function() {
equalHeight($(".left"));
equalHeight($(".right"));
});
});
8. 字体大小调整(Font resizing)
$(document).ready(function() {
// Reset the font size(back to default)
var originalFontSize = $('html').css('font-size');
$(".resetFont").click(function(){
$('html').css('font-size', originalFontSize);
});
// Increase the font size(bigger font0
$(".increaseFont").click(function(){
var currentFontSize = $('html').css('font-size');
var currentFontSizeNum = parseFloat(currentFontSize, 10);
var newFontSize = currentFontSizeNum*1.2;
$('html').css('font-size', newFontSize);
return false;
});
// Decrease the font size(smaller font)
$(".decreaseFont").click(function(){
var currentFontSize = $('html').css('font-size');
var currentFontSizeNum = parseFloat(currentFontSize, 10);
var newFontSize = currentFontSizeNum*0.8;
$('html').css('font-size', newFontSize);
return false;
});
});
9. 返回页面顶部(Smooth(animated) page scroll)
$(document).ready(function() {
$('a[href*=#]').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
&& location.hostname == this.hostname) {
var $target = $(this.hash);
$target = $target.length && $target
|| $('[name=' + this.hash.slice(1) +']');
if ($target.length) {
var targetOffset = $target.offset().top;
$('html,body')
.animate({scrollTop: targetOffset}, 900);
return false;
}
}
});
// how to use
// place this where you want to scroll to
<a name="top"></a>
// the link
<a href="#top">go to top</a>
});
文章由jquery分享网站整理
<!--------------------------------------------------------------------------->
11. 获取鼠标的xy坐标(Get the mouse cursor x and y axis)
$(document).ready(function() {
$().mousemove(function(e){
//display the x and y axis values inside the div with the id XY
$('#XY').html("X Axis : " + e.pageX + " | Y Axis " + e.pageY);
});
// how to use
<div id="XY"></div>
});
12. 验证元素是否为空(Verify if an Element is empty)
$(document).ready(function() {
if ($('#id').html()) {
// do something
}
});
13. 替换元素(Replace a element)
$(document).ready(function() {
$('#id').replaceWith('
<div>I have been replaced</div>
');
});
14. 延迟加载(jQuery timer callback functions)
$(document).ready(function() {
window.setTimeout(function() {
// do something
}, 1000);
});
15. 移除单词(Remove a word)
$(document).ready(function() {
var el = $('#id');
el.html(el.html().replace(/word/ig, ""));
});
16. 验证元素是否存在(Verify that an element exists in jQuery)
$(document).ready(function() {
if ($('#id').length) {
// do something
}
});
17. 使整个DIV可点击(Make the entire DIV clickable)
$(document).ready(function() {
$("div").click(function(){
//get the url from href attribute and launch the url
window.location=$(this).find("a").attr("href"); return false;
});
// how to use
<div><a href="index.html">home</a></div>
});
18. id和class切换(Switch between classes or id’s when resizing the window)
$(document).ready(function() {
function checkWindowSize() {
if ( $(window).width() > 1200 ) {
$('body').addClass('large');
}
else {
$('body').removeClass('large');
}
}
$(window).resize(checkWindowSize);
});
文章由jquery分享网站整理
<!--------------------------------------------------------------------------->
19. 克隆对象(Clone a object)
$(document).ready(function() {
var cloned = $('#id').clone();
// how to use
<div id="id"></div>
});
20. 使元素居中屏幕(Center an element on the screen)
$(document).ready(function() {
jQuery.fn.center = function () {
this.css("position","absolute");
this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
return this;
}
$("#id").center();
});
21. 自定义选择器(Write our own selector)
$(document).ready(function() {
$.extend($.expr[':'], {
moreThen1000px: function(a) {
return $(a).width() > 1000;
}
});
$('.box:moreThen1000px').click(function() {
// creating a simple js alert box
alert('The element that you have clicked is over 1000 pixels wide');
});
});
22. 统计元素个数(Count a element)
$(document).ready(function() {
$("p").size();
});
23. 自定义Bullets(Use Your Own Bullets)
//Example 1
<script src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1.2.6");
google.setOnLoadCallback(function() {
// do something
});
</script><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"
type="text/javascript"></script>
// Example 2:(the best and fastest way)
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
25. 禁用jQuery动画(Disable jQuery animations)
$(document).ready(function() {
jQuery.fx.off = true;
});
26. 防止不兼容冲突(No conflict-mode)
$(document).ready(function() {
var $jq = jQuery.noConflict();
$jq('#id').show();
});
文章由jquery分享网站整理
<!--------------------------------------------------------------------------->