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我们可以判断一个链接是否是外部的,万花楼论坛 www.whlwang.com并来添加一个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>

jQuery 中的 39 个技巧的更多相关文章

  1. jQuery 中的 39 个技巧【申明:来源于网络】

    jQuery 中的 39 个技巧[申明:来源于网络] 地址:http://blog.csdn.net/zhongqi2513/article/details/53704812?ref=myread

  2. jQuery中的100个技巧

      1.当document文档就绪时执行JavaScript代码. 我们为什么使用jQuery库呢?原因之一就在于我们可以使jQuery代码在各种不同的浏览器和存在bug的浏览器上完美运行. < ...

  3. jQuery中的100个技巧(译)

    1.当document文档就绪时执行JavaScript代码. 我们为什么使用jQuery库呢?原因之一就在于我们可以使jQuery代码在各种不同的浏览器和存在bug的浏览器上完美运行. <sc ...

  4. jquery获取json对象中的key小技巧

    jquery获取json对象中的key小技巧 比如有一个json var json = {"name" : "Tom", "age" : 1 ...

  5. 使用jQuery+huandlebars循环中索引(@index)使用技巧(访问父级索引)

    兼容ie8(很实用,复制过来,仅供技术参考,更详细内容请看源地址:http://www.cnblogs.com/iyangyuan/archive/2013/12/12/3471227.html) & ...

  6. jQuery源码分析-jQuery中的循环技巧

    作者:nuysoft/JS攻城师/高云 QQ:47214707 EMail:nuysoft@gmail.com 声明:本文为原创文章,如需转载,请注明来源并保留原文链接. 前记:本文收集了jQuery ...

  7. 前端开发入门到进阶附录一【JQuery中parent(),parents(),parentsUntil()区别和使用技巧】

    JQuery中parent(),parents(),parentsUntil()区别和使用技巧:https://blog.csdn.net/china1223/article/details/5193 ...

  8. jquery中ajax用return来返回值无效

    jquery中,ajax返回值,有三种写法,只有其中一种是成功的 /** * async:false,同步调用 * 返回1:2 * 失败 * 分析:ajax内部是一个或多个定义的函数,ajax中ret ...

  9. Web前端之jQuery 的10大操作技巧

    不管是做什么事情,人们习惯在工作中去找方法.找技巧,来帮助提高效率,在软件开发中更是如此.jQuery作为前端开发必学技术之一,在使用中也有各种各样的小技巧,今天小编为大家分享10条必知会的技巧,希望 ...

随机推荐

  1. HTML中使用javascript解除禁止input输入框代码:

    转:表单中Readonly和Disabled的区别 参考资料: disabled和readonly区别: 参考博文1地址:http://blog.csdn.net/symgdwyh/article/d ...

  2. Rafy 领域实体框架 - 树型实体功能(自关联表)

      在 Rafy 领域实体框架中,对自关联的实体结构做了特殊的处理,下面对这一功能进行讲解. 场景 在开发数据库应用程序时,往往会遇到自关联表的场景.例如,分类信息.组织架构中的部门.文件夹信息等,都 ...

  3. Javascript贪食蛇小游戏

    试玩:http://hovertree.com/game/9/ 贪吃蛇是一种风靡全球的小游戏,就是一条小蛇,不停地在屏幕上游走,吃各个方向出现的蛋,越吃越长.只要蛇头碰到屏幕四周,或者碰到自己的身子, ...

  4. C#之tcp自动更新程序

    .NETTCP自动更新程序有如下几步骤: 第一步:服务端开启监听 ServiceHost host; private void button1_Click(object sender, EventAr ...

  5. [译]Godot系列教程二 - 场景实例化(Instancing)

    场景实例化(Instancing) 原理阐述 创建一个场景并将节点扔到里面对于小项目是适用的,但随着项目不断发展,用到越来越多的节点,整个项目很快就会演化成难以管理的状态. 为了解决这个问题,Godo ...

  6. laravel5 数据库配置(MySQL)

    laravel5 数据库配置(MySQL) 首先有一个安装完成可以运行的laravel框架. 配置database.php 进入laravel根目录. 在config目录下找到database.php ...

  7. ahjesus HttpQuery

    /// <summary> /// 有关HTTP请求的辅助类 /// </summary> public class HttpQuery { private static re ...

  8. Web 前端开发精华文章集锦(jQuery、HTML5、CSS3)【系列十七】

    <Web 前端开发精华文章推荐>2013年第五期(总第十七期)和大家见面了.梦想天空博客关注 前端开发 技术,分享各种增强网站用户体验的 jQuery 插件,展示前沿的 HTML5 和 C ...

  9. git 提交解决冲突

    一:git命令在提交代码前,没有pull拉最新的代码,因此再次提交出现了冲突. error: You have not concluded your merge (MERGE_HEAD exists) ...

  10. 3D banner(CSS3+HTML5)

    1.这是一篇 3Dbanner制作的简易流程,支持高版本的chrome和firefox浏览器,俩浏览器显示可能会有些差异 2.没有兼容性代码,因为仅仅只是熟悉流程,希望小伙伴们自己改善哈(>﹏& ...