微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

jQuery中的100个技巧汇总

1.当document文档就绪时执行JavaScript代码

我们为什么使用jQuery库呢?原因之一就在于我们可以使jQuery代码在各种不同的浏览器和存在bug的浏览器上完美运行。

rush:js;">

2.使用route。

rush:js;">

3.使用JavaScript中的AND技巧。

使用&&操作符的特点是如果操作符左边的表达式是false,那么它就不会再判断操作符右边的表达式了。所以:

rush:js;"> // Instead of writing this: if($('#elem').length){ // do something } // You can write this: $('#elem').length && log("doing something");

4. is()方法比你想象的更为强大。

下面举几个例子,我们先写一个id为elem的div。js代码如下:

rush: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();方法可以判断网页的元素数量

rush:js;"> // How many elements does your page have? log('This page has ' + $('*').length + ' elements!');

6.使用length()属性很笨重,下面我们使用exist()方法

0; } log($('#elem').exists() ? "exists!" : "doesn't exist!");

7.jQuery方法$()实际上是拥有两个参数的,你知道第二个参数的作用吗?

rush:js;"> // 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 = $('

',{
"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我们可以判断一个链接是否是外部的,并来添加一个icon在非外部链接中,且确定打开方式。

这里用到了hostname属性

9.jQuery中的end()方法可以使你的jQuery链更加高效。

rush:js;">
// 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认事件。

rush:js;">

11.一些站点可能会使你的网页在一个bar下面,即我们所看到在下面的网页是iframe标签中的,我们可以这样解决

rush:js;"> // 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.你的内联样式表并不是被设置为不可改变的

,如下:

rush:js;"> // Make the stylesheet visible and editable $('#regular-style-block').css({'display':'block','white-space':'pre'}) .attr('contentEditable',true);

这样即可改变内联样式了。

13.有时候我们不希望网页的某一部分内容被选择比如复制粘贴这种事情

,我们可以这么做:

rush:js;">

这样,内容就不能被选择啦。

14.从CDN中引入jQuery,这样的方法可以提高我们网站的性能,并且引入最新的版本也是一个不错的主意。

下面会介绍四种不同的方法

rush:js;">

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐