jQuery中的100个技巧汇总


Posted in Javascript onDecember 15, 2016

1.当document文档就绪时执行JavaScript代码。

我们为什么使用jQuery库呢?原因之一就在于我们可以使jQuery代码在各种不同的浏览器和存在bug的浏览器上完美运行。

<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
 <script>
 // Different ways to achieve the Document Ready event
 // With jQuery
 $(document).ready(function(){ /* ... */});
 // Short jQuery
 $(function(){ /* ... */});
 // Without jQuery (doesn't work in older IE versions)
 document.addEventListener('DOMContentLoaded',function(){
 // Your code goes here
 });
 // The Trickshot (works everywhere):
 r(function(){
 alert('DOM Ready!');
 })
 function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}
 </script>

 2.使用route。

<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
 <script>
 var route = {
 _routes : {}, // The routes will be stored here
 add : function(url, action){
 this._routes[url] = action;
 },
 run : function(){
 jQuery.each(this._routes, function(pattern){
 if(location.href.match(pattern)){
 // "this" points to the function to be executed
 this();
 }
 });
 }
 }
 // Will execute only on this page:
 route.add('002.html', function(){
 alert('Hello there!')
 });
 route.add('products.html', function(){
 alert("this won't be executed :(")
 });
 // You can even use regex-es:
 route.add('.*.html', function(){
 alert('This is using a regex!')
 });
 route.run();
 </script>

3.使用JavaScript中的AND技巧。

使用&&操作符的特点是如果操作符左边的表达式是false,那么它就不会再判断操作符右边的表达式了。所以:

// Instead of writing this:
if($('#elem').length){
 // do something
}
// You can write this:
$('#elem').length && log("doing something");

4. is()方法比你想象的更为强大。

下面举几个例子,我们先写一个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!");
// Animating
elem.animate({'width':200},1);
// is it animated?
elem.is(':animated') && log("it is animated!");

其中判断是否为动画我觉得非常不错。

5.判断你的网页一共有多少元素。

 通过使用$("*").length();方法可以判断网页的元素数量。

// How many elements does your page have?
log('This page has ' + $('*').length + ' elements!');

6.使用length()属性很笨重,下面我们使用exist()方法。

/ Old way
log($('#elem').length == 1 ? "exists!" : "doesn't exist!");
// Trickshot:
jQuery.fn.exists = function(){ return this.length > 0; }
log($('#elem').exists() ? "exists!" : "doesn't exist!");

7.jQuery方法$()实际上是拥有两个参数的,你知道第二个参数的作用吗?

// 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 called

var div = $('<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');

8.使用jQuery我们可以判断一个链接是否是外部的,并来添加一个icon在非外部链接中,且确定打开方式。

这里用到了hostname属性。

<ul id="links"> 
 <li><a href="007.html">The previous tip</a></li> 
 <li><a href="./009.html">The next tip</a></li>
 <li><a href="http://www.google.com/">Google</a></li> 
</ul>
// Loop through all the links
$('#links a').each(function(){
 if(this.hostname != location.hostname){
 // The link is external
 $(this).append('<img src="assets/img/external.png" />')
 .attr('target','_blank');
 }
});

9.jQuery中的end()方法可以使你的jQuery链更加高效。

<ul id="meals"> <li> <ul class="breakfast"> <li class="eggs">No</li> <li class="toast">No</li> <li class="juice">No</li> </ul> </li> </ul>
// Here is how it is used:
var breakfast = $('#meals .breakfast');
breakfast.find('.eggs').text('Yes')
 .end() // back to breakfast
 .find('.toast').text('Yes')
 .end()
 .find('.juice').toggleClass('juice coffee').text('Yes');
breakfast.find('li').each(function(){
 log(this.className + ': ' + this.textContent)
});

10.也许你希望你的web 应用感觉更像原生的,那么你可以阻止contextmenu默认事件。

<script>
 // Prevent right clicking on this page
 $(function(){
 $(document).on("contextmenu",function(e){
 e.preventDefault();
 });
 });
</script>

11.一些站点可能会使你的网页在一个bar下面,即我们所看到在下面的网页是iframe标签中的,我们可以这样解决。

// 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.');
}

12.你的内联样式表并不是被设置为不可改变的,如下:

// Make the stylesheet visible and editable
$('#regular-style-block').css({'display':'block', 'white-space':'pre'})
 .attr('contentEditable',true);

这样即可改变内联样式了。

13.有时候我们不希望网页的某一部分内容被选择比如复制粘贴这种事情,我们可以这么做:

<p class="descr">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.</p>
<script>
// Prevent text from being selected
 $(function(){
 $('p.descr').attr('unselectable', 'on')
 .css('user-select', 'none')
 .on('selectstart', false);
 });
</script>

这样,内容就不能被选择啦。

14.从CDN中引入jQuery,这样的方法可以提高我们网站的性能,并且引入最新的版本也是一个不错的主意。

下面会介绍四种不同的方法。

<!-- Case 1 - requesting jQuery from the official CDN -->
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<!-- Case 2 - requesting jQuery from Google's CDN (notice the protocol) -->
<!-- <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> -->
<!-- Case 3 - requesting the latest minor 1.8.x version (only cached for an hour) -->
<!-- <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10/jquery.min.js"></script> -->
<!-- Case 4 - requesting the absolute latest jQuery version (use with caution) -->
<!-- <script src="http://code.jquery.com/jquery.min.js"></script> -->

15.保证最小的DOM操作。

我们知道js操作DOM是非常浪费资源的,我们可以看看下面的例子。

CODE
// Bad
//var elem = $('#elem');
//for(var i = 0; i < 100; i++){
// elem.append('<li>element '+i+'</li>');
//}
// Good
var elem = $('#elem'),
 arr = [];
for(var i = 0; i < 100; i++){
 arr.push('<li>element '+i+'</li>');
}
elem.append(arr.join(''));

16.更方便的分解URL。

也许你会使用正则表达式来解析URL,但这绝对不是一种好的方法,我们可以借用a标签来实现它。

// You want to parse this address into parts:
var url = 'http://tutorialzine.com/books/jquery-trickshots?trick=12#comments';
// The trickshot:
var a = $('<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'));

17.不要害怕使用vanilla.js。

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);
});

18.最优化你的选择器

// 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')

19.缓存你的selector。

// 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();

20.对于重复的函数只定义一次

如果你追求代码的更高性能,那么当你设置事件监听程序时必须小心,只定义一次函数然后把它的名字作为事件处理程序传递是不错的方法。

$(document).ready(function(){
 function showMenu(){
 alert('Showing menu!');
 // Doing something complex here
 }
 $('#menuButton').click(showMenu);
 $('#menuLink').click(showMenu);
});

21.像对待数组一样地对待jQuery对象

由于jQuery对象有index值和长度,所以这意味着我们可以把对象当作普通的数组对待。这样也会有更好地性能。

var arr = $('li'),
 iterations = 100000;
timer('Native Loop');
for(var z=0;z<iterations;z++){
 var length = arr.length;
 for(var i=0; i < length; i++){
 arr[i];
 }
}
timer_result('Native Loop');
timer('jQuery Each');
for(z=0;z<iterations;z++){
 arr.each(function(i, val) {
 this;
 });
}
timer_result('jQuery Each');

未完待续...

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持三水点靠木!

Javascript 相关文章推荐
js实现简单模态窗口,背景灰显
Nov 14 Javascript
jquery.boxy插件的iframe扩展代码
Jul 02 Javascript
ajax处理php返回json数据的实例代码
Jan 24 Javascript
禁止空格提交表单的js代码
Nov 17 Javascript
jQuery中mouseover事件用法实例
Dec 26 Javascript
JavaScript获得当前网页来源页面(即上一页)的方法
Apr 03 Javascript
浅谈javascript中基本包装类型
Jun 03 Javascript
在ASP.NET MVC项目中使用RequireJS库的用法示例
Feb 15 Javascript
相册展示PhotoSwipe.js插件实现
Aug 25 Javascript
Webpack打包慢问题的完美解决方法
Mar 16 Javascript
使用SVG基本操作API的实例讲解
Sep 14 Javascript
QRCode.js二维码生成并能长按识别
Oct 16 Javascript
JavaScript 输出显示内容(document.write、alert、innerHTML、console.log)
Dec 14 #Javascript
详解jQuery中的事件
Dec 14 #Javascript
JS实现鼠标移上去显示图片或微信二维码
Dec 14 #Javascript
微信小程序 HTTPS报错整理常见问题及解决方案
Dec 14 #Javascript
node.js报错:Cannot find module 'ejs'的解决办法
Dec 14 #Javascript
原生JS获取元素集合的子元素宽度实例
Dec 14 #Javascript
微信小程序 require机制详解及实例代码
Dec 14 #Javascript
You might like
用PHP将数据导入到Foxmail的实现代码
2010/09/05 PHP
ThinkPHP3.1.3版本新特性概述
2014/06/19 PHP
ThinkPHP模板输出display用法分析
2014/11/26 PHP
使用PHPExcel操作Excel用法实例分析
2015/03/26 PHP
百度地图API使用方法详解
2015/08/25 PHP
关于扩展 Laravel 默认 Session 中间件导致的 Session 写入失效问题分析
2016/01/08 PHP
php数组冒泡排序算法实例
2016/05/06 PHP
php使用filter_var函数判断邮箱,url,ip格式示例
2019/07/06 PHP
学习Bootstrap组件之下拉菜单
2015/07/28 Javascript
js判断文件格式及大小的简单实例(必看)
2016/10/11 Javascript
深入研究jQuery图片懒加载 lazyload.js使用方法
2017/08/16 jQuery
vue.extend实现alert模态框弹窗组件
2018/04/28 Javascript
Vue源码探究之状态初始化
2018/11/14 Javascript
微信小程序wx.request的简单封装
2019/11/13 Javascript
Vue实现剪切板图片压缩功能
2020/02/04 Javascript
如何使用vue slot创建一个模态框的实例代码
2020/05/24 Javascript
[06:13]DOTA2进化论(修改版)
2013/10/08 DOTA
Python中optionParser模块的使用方法实例教程
2014/08/29 Python
Python模拟登录12306的方法
2014/12/30 Python
Python使用正则表达式过滤或替换HTML标签的方法详解
2017/09/25 Python
使用pip发布Python程序的方法步骤
2018/10/11 Python
Python如何筛选序列中的元素的方法实现
2019/07/15 Python
基于python实现微信好友数据分析(简单)
2020/02/16 Python
简单了解pytest测试框架setup和tearDown
2020/04/14 Python
keras导入weights方式
2020/06/12 Python
python如何将图片转换素描画
2020/09/08 Python
如何使用 Flask 做一个评论系统
2020/11/27 Python
Saks Fifth Avenue澳洲/亚太地区:萨克斯第五大道精品百货店
2019/06/09 全球购物
丝芙兰墨西哥官网:Sephora墨西哥
2020/05/30 全球购物
会计自我鉴定范文
2013/10/06 职场文书
高三高考决心书
2014/03/11 职场文书
省级优秀班集体申报材料
2014/05/25 职场文书
学生保证书
2015/01/16 职场文书
幼儿园教师个人总结
2015/02/05 职场文书
2016年教师节贺卡寄语
2015/12/04 职场文书
解决Navicat for MySQL 连接 MySQL 报2005错误的问题
2021/05/29 MySQL