jQuery 中的 39 个技巧
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 个技巧的更多相关文章
- jQuery 中的 39 个技巧【申明:来源于网络】
jQuery 中的 39 个技巧[申明:来源于网络] 地址:http://blog.csdn.net/zhongqi2513/article/details/53704812?ref=myread
- jQuery中的100个技巧
1.当document文档就绪时执行JavaScript代码. 我们为什么使用jQuery库呢?原因之一就在于我们可以使jQuery代码在各种不同的浏览器和存在bug的浏览器上完美运行. < ...
- jQuery中的100个技巧(译)
1.当document文档就绪时执行JavaScript代码. 我们为什么使用jQuery库呢?原因之一就在于我们可以使jQuery代码在各种不同的浏览器和存在bug的浏览器上完美运行. <sc ...
- jquery获取json对象中的key小技巧
jquery获取json对象中的key小技巧 比如有一个json var json = {"name" : "Tom", "age" : 1 ...
- 使用jQuery+huandlebars循环中索引(@index)使用技巧(访问父级索引)
兼容ie8(很实用,复制过来,仅供技术参考,更详细内容请看源地址:http://www.cnblogs.com/iyangyuan/archive/2013/12/12/3471227.html) & ...
- jQuery源码分析-jQuery中的循环技巧
作者:nuysoft/JS攻城师/高云 QQ:47214707 EMail:nuysoft@gmail.com 声明:本文为原创文章,如需转载,请注明来源并保留原文链接. 前记:本文收集了jQuery ...
- 前端开发入门到进阶附录一【JQuery中parent(),parents(),parentsUntil()区别和使用技巧】
JQuery中parent(),parents(),parentsUntil()区别和使用技巧:https://blog.csdn.net/china1223/article/details/5193 ...
- jquery中ajax用return来返回值无效
jquery中,ajax返回值,有三种写法,只有其中一种是成功的 /** * async:false,同步调用 * 返回1:2 * 失败 * 分析:ajax内部是一个或多个定义的函数,ajax中ret ...
- Web前端之jQuery 的10大操作技巧
不管是做什么事情,人们习惯在工作中去找方法.找技巧,来帮助提高效率,在软件开发中更是如此.jQuery作为前端开发必学技术之一,在使用中也有各种各样的小技巧,今天小编为大家分享10条必知会的技巧,希望 ...
随机推荐
- 4.Java网络编程之TCP/UDP
常见传输协议: UDP , TCP UDP协议: 特点: 1.将数据及源和目的封装成数据包中,不需要建立连接 2.每个数据包的大小限制在64K内 ...
- CentOS6.5网络设置
CentOS6.5网络设置 不知道哪里做错了,长时间无法连接网络,百度了各种还是不可以.最后自己提取了以前可以联网的配置粘贴过来,成功.配置文件内容如下: vim /etc/resolv.conf 1 ...
- Elasticsearch 教程--数据
在Elasticsearch中,每一个文档都有一个版本号码.每当文档产生变化时(包括删除),_version就会增大.在<版本控制>中,我们将会详细讲解如何使用_version的数字来确认 ...
- 特性(C#)
特性(Attribute)是用于在运行时传递程序中各种元素(比如类.方法.结构.枚举.组件等)的行为信息的声明性标签,可以为程序集.类型,以及类型内部的各种成员添加扩展信息,用于表示一些附加信息.您可 ...
- 【Basics of Entity Framework】【EF基础系列1】
EF自己包括看视频,看MSDN零零散散的学了一点皮毛,这次打算系统学习一下EF.我将会使用VS2012来学习这个EF基础系列. 现在看看EF的历史吧: EF版本 相关版本特性介绍 EF3.5 基于数据 ...
- 【WCF】WCF中的InstanceContext与ConcurrencyMode【转】
一.前言 最近忙于公司的在线升级项目,一个人要负责公司四大产品的在线升级,这四个产品是在Revit中以插件形式存在的,目前基于WCF来实现.等客户总量突破5万了,再重新用socket实现. 由于有服务 ...
- MVC 自定义Htmlhelper扩展
在MVC中,我们不仅可以使用它原来的方法,我们还可以自定义,这不不仅加大了我们开发的效率,同时使界面更简洁. 具体什么是扩展方法,你可以这样理解,必须是静态且在形参中第一个参数是以this开头,大概先 ...
- 从零开始学 Java - Spring MVC 实现跨域资源 CORS 请求
论职业的重要性 问:为什么所有家长都希望自己的孩子成为公务员? 答:体面.有权.有钱又悠闲. 问:为什么所有家长都希望自己的孩子成为律师或医生? 答:体面.有钱.有技能. 问:为什么所有家长都不怎么知 ...
- ATM跨行取款的清算方式
ATM跨行取款和POS机是类似的,因为没有商户参与,所以不需要收单清算,过程更为简单. 回到文章最开头的例子:你拿着一张工行卡去建行的ATM取了100元,这个跨行业务在CNAPS体系中的过程如下: 你 ...
- 更新整理本人所有博文中提供的代码与工具(Java,2014.01)
为了更方便地管理博文中涉及的各种代码与工具资源,现在把这些资源迁移到 Google Code 中,有兴趣者可前往下载. Java 1.<高效 Java Web 应用开发框架 JessMA v3. ...