全网整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:400-708-3566

jQuery中的100个技巧汇总

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

未完待续...

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


# jquery  # 技巧  # jquery实用技巧之输入框提示语句  # jQuery操作Table技巧大汇总  # Jquery使用小技巧汇总  # jQuery操作表格(table)的常用方法、技巧汇总  # jquery常用技巧及常用方法列表集合  # jQuery基础学习技巧总结  # jQuery使用技巧简单汇总  # jQuery提交多个表单的小技巧  # 高效的jQuery代码编写技巧总结  # 前端开发必知的15个jQuery小技巧  # 我们可以  # 几个  # 如果你  # 是一种  # 会有  # 太多  # 我觉得  # 你可以  # 你会  # 可以用  # 当你  # 你知道  # 第二个  # 更高  # 就不能  # 绝对不  # 但这  # 会使  # 使你  # 原因之一 


相关文章: 如何安全更换建站之星模板并保留数据?  建站主机是否等同于虚拟主机?  如何用已有域名快速搭建网站?  php json中文编码为null的解决办法  台州网站建设制作公司,浙江手机无犯罪记录证明怎么开?  如何在IIS中新建站点并配置端口与物理路径?  成都网站制作报价公司,成都工业用气开户费用?  内部网站制作流程,如何建立公司内部网站?  C++如何使用std::optional?(处理可选值)  如何选择适合PHP云建站的开源框架?  如何在云虚拟主机上快速搭建个人网站?  哪家制作企业网站好,开办像阿里巴巴那样的网络公司和网站要怎么做?  潍坊网站制作公司有哪些,潍坊哪家招聘网站好?  小视频制作网站有哪些,有什么看国内小视频的网站,求推荐?  如何高效配置IIS服务器搭建网站?  惠州网站建设制作推广,惠州市华视达文化传媒有限公司怎么样?  儿童网站界面设计图片,中国少年儿童教育网站-怎么去注册?  如何在Windows服务器上快速搭建网站?  宠物网站制作html代码,有没有专门介绍宠物如何养的网站啊?  武汉网站制作费用多少,在武汉武昌,建面100平方左右的房子,想装暖气片,费用大概是多少啊?  制作网站的模板软件,网站怎么建设?  常州自助建站:操作简便模板丰富,企业个人快速搭建网站  广东企业建站网站优化与SEO营销核心策略指南  天津个人网站制作公司,天津网约车驾驶员从业资格证官网?  深圳 网站制作,深圳招聘网站哪个比较好一点啊?  建站之星安装提示数据库无法连接如何解决?  简历在线制作网站免费版,如何创建个人简历?  如何通过NAT技术实现内网高效建站?  已有域名能否直接搭建网站?  移动端手机网站制作软件,掌上时代,移动端网站的谷歌SEO该如何做?  如何快速搭建FTP站点实现文件共享?  建站之星导航配置指南:自助建站与SEO优化全解析  企业网站制作公司网页,推荐几家专业的天津网站制作公司?  湖州网站制作公司有哪些,浙江中蓝新能源公司官网?  建站之星代理费用多少?最新价格详情介绍  如何挑选高效建站主机与优质域名?  胶州企业网站制作公司,青岛石头网络科技有限公司怎么样?  如何在云指建站中生成FTP站点?  公司网站的制作公司,企业网站制作基本流程有哪些?  高端建站如何打造兼具美学与转化的品牌官网?  建站之星导航菜单设置与功能模块配置全攻略  高端企业智能建站程序:SEO优化与响应式模板定制开发  企业在线网站设计制作流程,想建设一个属于自己的企业网站,该如何去做?  宝塔面板如何快速创建新站点?  车管所网站制作流程,交警当场开简易程序处罚决定书,在交警网站查询不到怎么办?  太原网站制作公司有哪些,网约车营运证查询官网?  如何在云主机快速搭建网站站点?  如何通过服务器快速搭建网站?完整步骤解析  如何基于云服务器快速搭建个人网站?  一键制作网站软件下载安装,一键自动采集网页文档制作步骤? 

您的项目需求

*请认真填写需求信息,我们会在24小时内与您取得联系。