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. Cesium应用篇:1快速搭建

    范例中所有范例可以在Github中搜索:ExamplesforCesium Cesium ['siːzɪəm]是一款开源的JavaScript开源库,开发者通过Cesium,实现无插件的创建三维球和二 ...

  2. 在.net中读写config文件的各种方法

    阅读目录 开始 config文件 - 自定义配置节点 config文件 - Property config文件 - Element config文件 - CDATA config文件 - Collec ...

  3. Moon.Orm版本维护及下载(跟踪报道)

    提示:最下面有最新的下载地址  历史记录: ).-- :: 支持Mysql,Sqlserver(点击下载) ).2013年9月14日,代码重构,加入oracle.复合主键功能(点击下载) )--,为d ...

  4. Asp.Net Core 通过中间件防止图片盗链

    一.原理 要实现防盗链,我们就必须先理解盗链的实现原理,提到防盗链的实现原理就不得不从HTTP协议说起,在HTTP协议中,有一个表头字段叫referer,采用URL的格式来表示从哪儿链接到当前的网页或 ...

  5. Javascript 如何生成Less和Js的Source map

    为什么有Source map CSS和JS脚本正变得越来越复杂,为了解决网络瓶颈,大部分源代码都需要经过编译.合并.压缩才能运用到实际环境中.为了减少网络资源占用,源码一般都会经过以下方式处理: 使用 ...

  6. 在Mac上开发使用yeoman构建Asp.net core项目并且实现分层引用

    1.Yeoman? yeoman是一个自动化脚手架工具.它提供很多generator,generator相当于VisualStudio的模板,用来初始化项目.更多的就不多说了,写一遍都写不完,自己看吧 ...

  7. Js apply方法详解

    我在一开始看到javascript的函数apply和call时,非常的模糊,看也看不懂,最近在网上看到一些文章对apply方法和call的一些示例,总算是看的有点眉目了,在这里我做如下笔记,希望和大家 ...

  8. MS SQL Server中数据表、视图、函数/方法、存储过程是否存在判断及创建

    前言 在操作数据库的时候经常会用到判断数据表.视图.函数/方法.存储过程是否存在,若存在,则需要删除后再重新创建.以下是MS SQL Server中的示例代码. 数据表(Table) 创建数据表的时候 ...

  9. [Asp.net 5] Logging-新日志系统目录

    楼主有个美好的愿望——把asp.net 5所有能看懂的代码一一呈现给大家(比如C++,楼主就看不懂).现在已经做完了依赖注入.多语言.配置文件三部分,比较基础的日志就成为了楼主的下一个目标.下面是楼主 ...

  10. redis主从复制 从而 数据备份和读写分离

    蜗牛Redis系列文章目录http://www.cnblogs.com/tdws/tag/NoSql/ 爬虫转载注明地址本文地址—博客园蜗牛 http://www.cnblogs.com/tdws/p ...