Home  >  Article  >  Web Front-end  >  Learn jQuery tips to improve your code_jquery

Learn jQuery tips to improve your code_jquery

WBOY
WBOYOriginal
2016-05-16 18:36:571094browse

jquery-技巧-教程

    jQuery之所以如此流行并被从大公司到个人博客的几乎每个人都广泛使用,是因为它上手和使用相当简单,而且为我们提供了一些人都不知道的相当棒的特性。我认为jQuery的大多数用户更趋向于使用jQuery插件来解决面临的难题,这通常是明智的选择。但是当插件相对于你的需求有一定缺陷的时候,你也许更应该想办法自己来解决,下面来看看这些实用的jQuery技巧,他们肯定会能够派上用场的!

1.测试并提升你的jQuery选择器水平

这个jQuery选择器实验室非常酷,它能在线免费使用,当然你也能下来到本地离线使用。这个测试页面包含复杂的HTML组合字段,然后你能尝试预定义使用各种jQuery选择器。如果这还不够你也可以自定义选择器。
jquery-选择器-技巧 

2.测试jQuery包装集是否包含某些元素

如果你想测试一下某个jQuery包装集中是否包含某些元素,你首先可以尝试使用验证首个元素是否存在:

if($(selector)[0]){...}
// 或者这样
if($(selector).length){...}

来看看这个例子:

//例子.如果你的页面有以下html代码
<ul id="shopping_cart_items">
    <li>
        <input class="in_stock" name="item" type="radio" value="Item-X" />Item X
    </li>
    <li>
        <input class="unknown" name="item" type="radio" value="Item-Y" />Item Y
    </li>
    <li>
        <input class="in_stock" name="item" type="radio" value="Item-Z" />Item Z
    </li>
</ul>
<pre escaped="true" lang="javascript">...
//这个if条件将返回true,因为我们有两个input域匹配了选择器,所以代码将会执行
if($('#shopping_cart_items input.in_stock')[0]){<statement>}
3.从jquery.org读取jQuery最新版本

你可以使用这句代码读取jQuery的最新版本的代码文件。

<script src="http://code.jquery.com/jquery-latest.js">script>

你可以使用这个方法来调用最近版本的jQuery框架,当然,你还可以使用下面这个代码从ajax.googleapis.com调用同样的最新版本jQuery:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript">script>
4.存储数据

使用data方法可以避免在DOM中存储数据,有些前端开发er喜欢使用HTML的属性来存储数据:

$('selector').attr('alt''data being stored');
//之后可以这样读取数据:
$('selector').attr('alt');

使用”alt”属性来作为参数名存储数据其实对于HTML来说是不符合语义的,我们可以使用jQuery的data方法来为页面中的某个元素存储数据:

$('selector').data('参数名''要存储的数据');
//之后这样取得数据:
$('selector').data('参数');

 

这个data方法能让你自己明明数据的参数,更语义更灵活,你可以在页面上的任何元素存储数据信息。如果想了解更多关于data()和removeData()方法的介绍,可以看看jQuery官方讲解

这个方法的经典应用是给input域一个默认值,然后在聚焦的时候清空它:
HTML部分:

<form id="testform">
    
<input type="text" class="clear" value="Always cleared" />
    
<input type="text" class="clear once" value="Cleared only once" />
    
<input type="text" value="Normal text" />
form>

JavaSript部分:

$( function() {
// Take out the input field with clear class
 // (Note: "clear once" is two classes: clear and once)
$('#testform input.clear').each( function() {
                                                                          
this).data("
txt", $.trim($ (this).val()));          }).focus(                           🎜>// When getting focus, determine whether the value in the field is the same as the default value. If it is the same, clear it >if
($.trim($(this
).val())
=== $ (this
).data("txt")) { ).blur( function() {
        
// 为有class clear的域添加blur时间来恢复默认值
            // 但如果class是once则忽略
            if ($.trim($(this).val()) === "" && !$(this).hasClass("once")) {
                
// Restore saved data
                $(this).val($(this).data("txt"));
            }
        });
});

查看Demo

5.jQuery手册常备身边

大多数人都很难记住所有的编程细节,即使再好的程序员也会有对某个程序语言的疏忽大意,所以把相关的手册打印出来或随时放在桌面上进行查阅绝对是可以提高编程效率的。
oscarotero jquery 1.3 (壁纸版)
jQuery手册

6.在FireBug控制台记录jQuery

FireBug是我最喜欢用的一个浏览器扩展工具之一,这个工具可以让你快速的在可视化界面中了解当前页面的HTML+CSS+JavaScript,并在该工具下完成即时开发。作为jQuery或JavaScript开发人员,FireFox对于记录你的JavaScript代码也得到支持。

写入FireBug控制台的最简单方式如下:

console.log("hello world")

firebug-jquery-控制台

你也可以按照你希望的方式写一些参数:

console.log(2,4,6,8,"foo",bar)

你也可以编写一个小扩展来记录jQuery对象到控制台:

jQuery.fn.log = function(msg) {
    console.log(
"%s: %o", msg, this);
    
return this;
};

// 对于这个扩展,你可以直接使用.log()方法来记录当前对象到控制台。
$('#some_div').find('li.source > input:checkbox').log("sources to uncheck").removeAttr("checked");
7.尽可能使用ID选择器

在使用jQuery之后,你会发现利用class属性来选择DOM元素变得相当简单。尽管如此,还是推荐大家尽量少用class选择器取而代之尽量多使用运行更快的ID选择器(IE浏览器下使用class选择器会在遍历整个DOM树之后返回相符的class包装集)。而ID选择器更快是因为 DOM本身就有”天然的”getElementById这个方法,而class并没有。所以如果使用class选择器的话,浏览器会遍历整个DOM,如果你的网页DOM结构足够复杂,这些class选择器足矣把页面拖得越来越慢。让我们看看这段简单的HTML代码:

<div id="main">
    
<form method="post" action="/">
        
<h2>
            Selectors in jQuery
        
h2>
        ... ...
        
<input class="button" id="main_button" type="submit" value="Submit" />
    
form>
div>

//使用class来调用submit按钮要比使用绝对的ID选择器慢很多

var main_button = $('#main .button');
var main_button = $('#main_button');
8.善于利用jQuery链

jQuery链不但允许以简洁的方式写出强大的操作,而且提高了开发效率,因为它能够把多个命令应用到包装集,而不必重新计算包装集。从而你不用再这样写了:

<li>Description: <input type="text" name="description" value="" />li>
$('#shopping_cart_items input.text').css('border''3px dashed yellow');
$(
'#shopping_cart_items input.text').css('background-color''red');
$(
'#shopping_cart_items input.text').val("text updated");

取而代之你可以使用jQuery链来完成简便的操作:

var input_text = $('#shopping_cart_items input.text');
input_text.css(
'border''3px dashed yellow');
input_text.css(
'background-color''red');
input_text.val(
"text updated");
// same with chaining:
var input_text = $('#shopping_cart_items input.text');
input_text.css(
'border''3px dashed yellow').css('background-color''red').val("text updated");
9.绑定jQuery函数到$(window).load事件

大多数jQuery实例或教程都告诉我们绑定我们的jQuery代码到$(document).ready事件。虽然$(document).ready事件在大多数情况下都OK,但是它的解析顺序是在文档准备就绪,单文档中的图片等对象正在下载的时候开始运行的。所以在某些时候使用$(document).ready事件并不一定能达到我们预期的效果,比如一些视觉效果和动画、拖拽、预读取隐藏图片等…通过使用$(window).load事件便可以安全的在整个文档都准备就绪之后再开始运行你期望的代码。

$(window).load( function() {
    
// 将你希望在页面完全就绪之后运行的代码放在这里
});
10.使用jQuery链来限定选择器,让你的代码更简洁更优雅

由于JavaScript支持链结构而且支持断行,所以你的代码可以写成下面这样,这个例子先在元素上移除一个class然后在同一个元素上添加另一个class:

$('#shopping_cart_items input.in_stock').removeClass('in_stock').addClass('3-5_days');

 

如果想让它更简单实用,你可以创建一个支持链结构的jQuery函数:

$.fn.makeNotInStock = function() {
    
return $(this).removeClass('in_stock').addClass('3-5_days');
}
$(
'#shopping_cart_items input.in_stock').makeNotInStock().log();
11.使用回调函数同步效果

如果你想确保某个事件或动画效果要在另一个事件运行之后再调用,那你就要使用回调函数了。你可以在这些动画效果后面绑定回调函数:slideDown( speed, [回调] ) ie. $(‘#sliding').slideDown('slow', function(){… 点击这里预览这个例子.

<style>
div.button 
{
    background
: #cfd;
    margin
: 3px;
    width
: 50px;
    text-align
: center;
    float
: left;
    cursor
: pointer;
    border
: 2px outset black;
    font-weight
: bolder;
}

#sliding 
{
    display
: none;
}
style>
$(document).ready( function() {
// Using jQuery’s click The event changes the visual effect and turns on the sliding effect
$("div.button").click( function() {
                                                 The effect below
inset",
cursor :
"wait"
});
        
// #sliding 现在将渐隐并在完成动作之后开启渐显效果
        // slideup once it completes
        $('#sliding').slideDown('slow'function() {
            $(
'#sliding').slideUp('slow'function() {
                
// 渐显效果完成后将会改变按钮的CSS属性
                $('div.button').css( {
                    borderStyle : 
"outset",
                    cursor : 
"auto"
                });
            });
        });
    });
});
12.学会使用自定义选择器

jQuery允许我们在css选择器的基础上定义自定义选择器来让我们的代码更简洁:

$.expr[':'$.expr[':'].mycustomselector= function(element, index, meta, stack){
// element- DOM element
 // index - the index value currently traversed in the stack
// meta - data element about your selector
 // stack - a stack used to iterate over all elements
 //
returns false if it does not contain the current element};
//
Application of custom selector:
$( '
.someClasses:test').doSomething();//
Let's take a look at a small example where we use a custom selector to lock the set of elements containing the "rel" attribute:
$.expr[ '
:'].withRel = function (element){ var $
this = $(element); // Only return elements whose rel attribute is not empty
 return
($this.attr('rel') != '');};

$(document).ready(
function(){
    
// 自定义选择器的使用很简单,它和其他选择器一样,返回一个元素包装集
    // 你可以为他使用格式方法,比如下面这样修改它的css样式
    $('a:withRel').css('background-color''green');
});
<ul>
    
<li>
        
<a href="#">without rela>
    
li>
    
<li>
        
<a rel="somerel" href="#">with rela>
    
li>
    
<li>
        
<a rel="" href="#">without rela>
    
li>
    
<li>
        
<a rel="nofollow" href="#">a link with rela>
    
li>
ul>
13. Preload images

Using JavaScript to preload images is usually a good idea:

//Function that defines the preloaded image list (with parameters)
jQuery.preloadImages = function() {
// Traverse the pictures
 for ( var i = 0; i&nbs
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn