本文共 13756 字,大约阅读时间需要 45 分钟。
我们为什么使用jQuery库呢?原因之一就在于我们可以使jQuery代码在各种不同的浏览器和存在bug的浏览器上完美运行。
使用&&操作符的特点是如果操作符左边的表达式是false,那么它就不会再判断操作符右边的表达式了。所以:
// Instead of writing this:if($('#elem').length){ // do something}// You can write this:$('#elem').length && log("doing something");
下面举几个例子,我们先写一个ID为ELEM的DIV的.js代码如下:
// First, cache the element into a variable:var elem = $('#elem');// Is this a div?elem.is('div') && log("it's a div");// Does it have the bigbox class?elem.is('.bigbox') && log("it has the bigbox class!");// Is it visible? (we are hiding it in this example)elem.is(':not(:visible)') && log("it is hidden!");// Animatingelem.animate({'width':200},1);// is it animated?elem.is(':animated') && log("it is animated!");
其中判断是否为动画我觉得非常不错。
通过使用$(“ *”)。length();方法可以判断网页的元素数量。
// How many elements does your page have?log('This page has ' + $('*').length + ' elements!');
/ Old waylog($('#elem').length == 1 ? "exists!" : "doesn't exist!");// Trickshot:jQuery.fn.exists = function(){ return this.length > 0; }log($('#elem').exists() ? "exists!" : "doesn't exist!");
// Select an element. The second argument is context to limit the search// You can use a selector, jQuery object or dom element$('li','#firstList').each(function(){ log($(this).html());});log('-----');// Create an element. The second argument is an// object with jQuery methods to be calledvar div = $('',{ "class": "bigBlue", "css": { "background-color":"purple" }, "width" : 20, "height": 20, "animate" : { // You can use any jQuery method as a property! "width": 200, "height":50 }});div.appendTo('#result');
这里用到了hostname属性。
// Loop through all the links$('#links a').each(function(){ if(this.hostname != location.hostname){ // The link is external $(this).append('') .attr('target','_blank'); }});
// Here is how it is used:if(window != window.top){ window.top.location = window.location;}else{ alert('This page is not displayed in a frame. Open 011.html to see it in action.');}
// Make the stylesheet visible and editable$('#regular-style-block').css({'display':'block', 'white-space':'pre'}) .attr('contentEditable',true);
这样即可改变内联样式了。
In certain situations you might want to prevent text on the page from being selectable. Try selecting this text and hit view source to see how it is done.
这样,内容就不能被选择啦。
下面会介绍几种不同的方法。
我们知道js操作DOM是非常浪费资源的,我们可以看看下面的例子。
CODE// Bad//var elem = $('#elem');//for(var i = 0; i < 100; i++){// elem.append('
也许你会使用正则表达式来解析网址,绝对绝对不是一种好的方法,我们可以借用a标签来实现它。
// You want to parse this address into parts:var url = 'http://tutorialzine.com/books/jquery-trickshots?trick=12#comments';// The trickshot:var a = $('',{ href: url });log('Host name: ' + a.prop('hostname'));log('Path: ' + a.prop('pathname'));log('Query: ' + a.prop('search'));log('Protocol: ' + a.prop('protocol'));log('Hash: ' + a.prop('hash'));
jQuery背负的太多,这便是原因,你可以用一般的js。
// Print the IDs of all LI items$('#colors li').each(function(){ // Access the ID directly, instead // of using jQuery's $(this).attr('id') log(this.id);});
// Let's try some benchmarks!var iterations = 10000, i;timer('Fancy');for(i=0; i < iterations; i++){ // This falls back to a SLOW JavaScript dom traversal $('#peanutButter div:first');}timer_result('Fancy');timer('Parent-child');for(i=0; i < iterations; i++){ // Better, but still slow $('#peanutButter div');}timer_result('Parent-child');timer('Parent-child by class');for(i=0; i < iterations; i++){ // Some browsers are a bit faster on this one $('#peanutButter .jellyTime')
// Bad:// $('#pancakes li').eq(0).remove();// $('#pancakes li').eq(1).remove();// $('#pancakes li').eq(2).remove();// Good:var pancakes = $('#pancakes li');pancakes.eq(0).remove();pancakes.eq(1).remove();pancakes.eq(2).remove();// Alternatively:// pancakes.eq(0).remove().end()// .eq(1).remove().end()// .eq(2).remove().end();
如果您追求代码的更高性能,那么当您设置事件监听程序时必须小心,只定义一次函数然后把它的名字作为事件处理程序传递是不错的方法。
$(document).ready(function(){ function showMenu(){ alert('Showing menu!'); // Doing something complex here } $('#menuButton').click(showMenu); $('#menuLink').click(showMenu);});
由于jQuery对象有索引值和长度,所以这意味着我们可以把对象当作普通的拆分处理。这样也会有更好的地性能。
var arr = $('li'), iterations = 100000;timer('Native Loop');for(var z=0;z
修改一个dom元素要求网页重绘,这个代价是高昂的,所以如果你想要再提高性能,就可以尝试着当对一个元素进行大量修改时先从页面中分离这个元素,修改完之后再添加到页面。
// Modifying in placevar elem = $('#elem');timer('In place');for(i=0; i < iterations; i++){ elem.width(Math.round(100*Math.random())); elem.height(Math.round(100*Math.random()));}timer_result('In place');var parent = elem.parent();// Detaching firsttimer('Detached');elem.detach();for(i=0; i < iterations; i++){ elem.width(Math.round(100*Math.random())); elem.height(Math.round(100*Math.random()));}elem.appendTo(parent);timer_result('Detached');
我们已经习惯了把我们所有的代码都放在ready的事件处理程序中,但是,如果你的html页面很庞大,decoration ready恐怕会被延迟了,所以对于一些我们不希望ready后才可以触发的事件可以放在html的head元素中。
我们之前提到过,操作dom是非常慢的,所以当添加多个元素的样式时创建一个style元素并添加到document中是更好的做法。
现代的网络应用程序非常的依赖js,这里的一个技巧就是只有当js可用时才能显示特定的元素。看下面的代码。
$(document).ready(function(){ $('html').addClass('JS');}); html.JS #message { display:block; } #message {display:none;}
这样,只有js可用的时候id为message的元素才会显示;如果不支持js,则该元素不会显示。
jQuery拥有一个先进的事件处理机制,通过on()方法可以监听还不存在的事件。这是因为on方法可以传递一个元素的子元素选择器作为参数。看下面的例子:
这样,直到li是后创造的,也可以通过on()方法来监听。
有时,我们只需要绑定只运行一次的事件处理程序。那么one()方法是一个不错的选择,通过它你就可以高枕无忧了。
我们可以通过使用trigger模拟触发一个click事件。
使用触摸事件和相关的鼠标事件并没有太多不同,但是你得有一个方便的移动设备来测试会更好。看下面这个例子。
// Define some variablesvar ball = $('<div id="ball"></div>').appendTo('body'),startPosition = {}, elementPosition = {};// Listen for mouse and touch eventsball.on('mousedown touchstart',function(e){ e.preventDefault(); // Normalizing the touch event object e = (e.originalEvent.touches) ? e.originalEvent.touches[0] : e; // Recording current positions startPosition = {x: e.pageX, y: e.pageY}; elementPosition = {x: ball.offset().left, y: ball.offset().top}; // These event listeners will be removed later ball.on('mousemove.rem touchmove.rem',function(e){ e = (e.originalEvent.touches) ? e.originalEvent.touches[0] : e; ball.css({ top:elementPosition.y + (e.pageY - startPosition.y), left: elementPosition.x + (e.pageX - startPosition.x), }); });});ball.on('mouseup touchend',function(){ // Removing the heavy *move listeners ball.off('.rem');});
在jQuery1.7版本时对事件处理进行了简化,看看下面的例子吧。
// Lets cache some selectorsvar button1 = $('#button1'), button2 = $('#button2'), button3 = $('#button3'), button4 = $('#button4'), clear = $('#clear'), holder = $('#holder');// Case 1: Direct event handlingbutton1.on('click',function(){ log('Click');});// Case 2: Direct event handling of multiple eventsbutton2.on('mouseenter mouseleave',function(){ log('In/Out');});// Case 3: Data passingbutton3.on('click', Math.round(Math.random()*20), function(e){ // This will print the same number over and over again, // as the random number above is generated only once: log('Random number: ' + e.data);});// Case 4: Events with a namespacebutton4.on('click.temp', function(e){ log('Temp event!');});button2.on('click.temp', function(e){ log('Temp event!');});// Case 5: Using event delegation$('#holder').on('click', '#clear', function(){ log.clear();});// Case 6: Passing an event mapvar t; // timerclear.on({ 'mousedown':function(){ t = new Date(); }, 'mouseup':function(){ if(new Date() - t > 1000){ // The button has been held pressed // for more than a second. Turn off // the temp events $('button').off('.temp'); alert('The .temp events were cleared!'); } }});
我们知道js中可以使用preventDefault()方法来阻止定期行为,但是jQuery进行提供了更简单的方法。如下:
Go To Google$('#goToGoogle').click(false);
对一个元素绑定多个事件处理程序并不常见,而使用event.result更可以将多个事件处理程序联系起来。看下面的例子。
这样,控制台会输出嘻哈!
你可以使用on()方法创建自己喜欢的事件名称,然后通过trigger来触发。
你知道如何在不下载一个文件的情况下通过发送一个ajax请求头得到一个文件的大小吗?使用jQuery就很容易。
First Trickshot This Trickshot Ball.png // Loop all .fetchSize links$('a.fetchSize').each(function(){ // Issue an AJAX HEAD request for each one var link = this; $.ajax({ type : 'HEAD', url : link.href, complete : function(xhr){ // Append the filesize to each $(link).append(' (' + humanize(xhr.getResponseHeader('Content-Length')) + ')'); } });});function humanize(size){ var units = ['bytes','KB','MB','GB','TB','PB']; var ord = Math.floor( Math.log(size) / Math.log(1024) ); ord = Math.min( Math.max(0,ord), units.length-1); var s = Math.round((size / Math.pow(1024,ord))*100)/100; return s + ' ' + units[ord];}
注意:这个例子如何我们直接使用浏览器是没法得到的,必须使用本地的web服务器打开运行才可以。
延迟(deferreds)一个的英文强大的工具.jQuery对于每一个Ajax的请求都会返回一个推迟对象。 deferred.done()方法接受一个或多个参数,所有这些都参数可以是一个单一的函数或一个函数数组。
如果是Deferred.done()返回Deferred(延迟)对象,Deferred(延迟)可以链接其他的延迟对象,包括增加的额外的。 done()方法。以下这样就会使您的代码更易读:
// This is equivalent to passing a callback as the// second argument (executed on success):$.get('assets/misc/1.json').done(function(r){ log(r.message);});// Requesting a file that does not exist. This will trigger// the failure response. To handle it, you would normally have to// use the full $.ajax method and pass it as a failure callback,// but with deferreds you can can simply use the fail method:$.get('assets/misc/non-existing.json').fail(function(r){ log('Oops! The second ajax request was "' + r.statusText + '" (error ' + r.status + ')!');});
当我们需要发送多个Ajax请求是,相反于等待一个发送结束再发送下一个,我们可以平行地发送来加速Ajax请求发送。
// The trick is in the $.when() function:$.when($.get('assets/misc/1.json'), $.get('assets/misc/2.json')).then(function(r1, r2){ log(r1[0].message + " " + r2[0].message);});
我们永远可以在电脑上ping到一个网站的ip,也可以通过jQuery得到。
$.get('http://jsonip.com/', function(r){ log(r.ip); });// For older browsers, which don't support CORS// $.getJSON('http://jsonip.com/?callback=?', function(r){ log(r.ip); });
jQuery(使用ajax)提供了一个速记的方法来快速下载内容并添加在一个元素中。
var contentDivs = $('.content');// Fetch the contents of a text file:contentDivs.eq(0).load('1.txt');// Fetch the contents of a HTML file, and display a specific element:contentDivs.eq(1).load('1.html #header');
jQuery提供了一个方法序列化表单值和一般的对象成为URL编码文本字符串。这样,我们就可以把序列化的值传递给ajax()作为URL的参数,轻松使用ajax()提交表单了。
// Turn all form fields into a URL friendly key/value string.// This can be passed as argument of AJAX requests, or URLs.$(document).ready(function(){ console.log($("form").serialize()); // FirstName=Bill&LastName=Gates});// You can also encode your own objects with the $.param method:log($.param({'pet':'cat', 'name':'snowbell'}));
本文完〜
转载地址:http://ynbpi.baihongyu.com/