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. SQLite关系型数据库

    SQLiteOpenHelper的使用:       首先声明一个DatabaseHelper类,这个类继承于SQLiteOpenHelper类,首先得有构造函数,声明DatabaseHelper类如 ...

  2. Mongoose使用案例--让JSON数据直接入库MongoDB

    目录 1.准备工作. 2.配置Mongoose. 3.创建目录及文件. 4.插入数据,POST提交JSON增加一条记录. 5.查询数据,取出你插入数据库的记录. 一.准备工作 使用Express4创建 ...

  3. jQuery方法position()与offset()区别

    参考别人写得比较明白的,红色部分为重点吧: 使用jQuery获取元素位置时,我们会使用position()或offset()方法,两个方法都返回一个包含两个属性的对象-左边距和上边距,它们两个的不同点 ...

  4. ie6,ie7,ie8 css bug兼容解决记录

    ie6,ie7,ie8 css bug兼容解决记录 转载自:ie6,ie7,ie8 css bug兼容解决记录 - 前端开发 断断续续的在开发过程中收集了好多的bug以及其解决的办法,都在这个文章里面 ...

  5. js修改不了input的值

    奇怪的input 今天想做一个通过点击按钮,修改input值的控件,但是点击按钮后,input值变成修改的值后又变回了原来的值,百思不得其解,代码如下 <form> <div cla ...

  6. 对于SQL Server,我需要多少内存

    经常被问到的一个问题:对于SQL Server,我需要多少内存?这个问题还是有同样的典型的“看情况而定”答案.在今天的文章里,我们来详细看下“看情况而定的”的不同方面. 全新SQL Server安装 ...

  7. 微信小程序,我的英雄列表

    最近微信小程序炒得火热,就跟成都的这个房价一样.昨天我也尝试了一下,做了一个自己的英雄列表.今天将自己的制作过程记录于此. 1.下载微信开发者工具 官网链接:https://mp.weixin.qq. ...

  8. Xamarin.Android之简单的抽屉布局

    0x01 前言 相信对于用过Android版QQ的,应该都不会陌生它那个向右滑动的菜单(虽说我用的是Lumia) 今天就用Xamarin.Android实现个比较简单的抽屉布局.下面直接进正题. 0x ...

  9. 设计模式(二)简单工厂模式(Simple Factory Pattern)

    一.引言 这个系列也是自己对设计模式的一些学习笔记,希望对一些初学设计模式的人有所帮助的,在上一个专题中介绍了单例模式,在这个专题中继续为大家介绍一个比较容易理解的模式——简单工厂模式. 二.简单工厂 ...

  10. jquery属性

    1.toggleClass()  如果对象有class属性,则删除: 如果没有class属性,则加上. <style> .hide{ display: none; } </style ...