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>

时间: 2024-08-11 09:42:08

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

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 //

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 //

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 //

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

Js代码   作者:nuysoft/JS攻城师/高云 QQ:47214707 EMail:[email protected] 声明:本文为原创文章,如需转载,请注明来源并保留原文链接. 前记:本文收集了jQuery中出现的各种遍历技巧和场景 Js代码   // 简单的for-in(事件) for ( type in events ) { } Js代码   // 缓存length属性,避免每次都去查找length属性,稍微提升遍历速度 // 但是如果遍历HTMLCollection时,性能提升非常

Handlebars.js循环中索引(@index)使用技巧(访问父级索引)

使用Handlebars.js过程中,难免会使用循环,比如构造数据表格.而使用循环,又经常会用到索引,也就是获取当前循环到第几次了,一般会以这个为序号显示在页面上. Handlebars.js中获取循环索引很简单,只需在循环中使用{{@index}}即可. 1 <!DOCTYPE html> 2 <html> 3 <head> 4 <META http-equiv=Content-Type content="text/html; charset=utf-

jquery中cookie用法实例详解(获取,存储,删除等)

这篇文章主要介绍了jquery中cookie用法,结合实例详细分析了jQuery操作cookie的获取,存储,删除等操作,并附带了Jquery操作Cookie记录用户查询过信息实现方法,需要的朋友可以参考下 本文实例讲述了jquery中cookie用法.分享给大家供大家参考,具体如下: cookie在jquery中有指定的cookie操作类,下面我先来介绍我们在使用cookie操作类时的一些问题,然后介绍正确的使用方法. 使用JQuery操作cookie时 发生取的值不正确的问题: 结果发现co

Jquery中$(document).ready() 和 JavaScript中的window.onload方法 比较

Jquery中$(document).ready()的作用类似于传统JavaScript中的window.onload方法,不过与window.onload方法还是有区别的. 1.执行时间 window.onload必须等到页面内包括图片的所有元素加载完毕后才能执行. $(document).ready()是DOM结构绘制完毕后就执行,不必等到加载完毕. 2.编写个数不同 window.onload不能同时编写多个,如果有多个window.onload方法,只会执行一个(最后一个)       

***浅析JQuery中的html(),text(),val()区别

jQuery中. html()用为读取和修改元素的HTML标签, text()用来读取或修改元素的纯文本内容, val()用来读取或修改表单元素的value值. 1.HTML html():取得第一个匹配元素的html内容.这个函数不能用于XML文档.但可以用于XHTML文档 html(val):设置每一个匹配元素的html内容.这个函数不能用于XML文档.但可以用于XHTML文档. 2.TEXT text():取得所有匹配元素的内容. 结果是由所有匹配元素包含的文本内容组合起来的文本.这个方法

关于JQuery中$.data绑定数据原理或逻辑

问题: JQuery中,对于.data([key],[value])函数,当使用其进行数据绑定时,假设要绑定的数据是“引用数据类型”,也就是对象:那么.data函数绑定的是该对象的副本还是该对象的一个引用?下面通过以下小例子来测试下: 1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Test<