扒一扒JQuery的几个技巧

1.jQuery方法$()实际上是拥有两个参数的

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('#eleID');

2.使用js给多个元素添加样式时更好的做法是创建一个style元素。

var style = $('<style>');
// Try commenting out this line, or change the color:
style.text('.div{ color:red;}');
style.prependTo('body');

3.阻止contextmenu默认事件。(右键菜单)

$(document).on("contextmenu",function(e){
    e.preventDefault();
});

4.监听不存在的元素上的事件。因为on方法可以传递一个元素的子元素选择器作为参数。

var list = $('#testList');
// Binding an event on the list, but listening for events on the li items:
list.on('click','li',function(){
    $(this).remove();
});
// This allows us to create li elements at a later time,
// while keeping the functionality(功能) in the event listener
list.append('<li>New item (click me!)</li>');

5.使用trigger模拟触发一个click等事件或其他自定义事件。

// Just a regular event listener:
press.on('click',function(e, how){
    how = how || '';
    alert('The buton was clicked ' + how + '!');
});

// Trigger the click event
press.trigger('click');

// Trigger it with an argument   也可以自定义事件
press.trigger('click',['fast']);

6.传递参数到e.data执行供执行的函数使用

//参数只会之心过一次,所以下面的random不管自行几次都是相同的结果
$(document).on('click', Math.round(Math.random()*20), function(e){
    // This will print the same number over and over again,
    // as the random number above is generated only once:
    console.log('Random number: ' + e.data,e.target);
});

7.Using event delegation 事件代理

$('#holder').on('click', '#clear', function(){
    clear();
});

8.绑定多个事件

clear.on('mouseup click',function(){
    //...
})

clear.on({
    'mousedown':function(){
       // ...
    },
    'mouseup':function(){
        // ...
    }
});

9.阻止默认事件

更快地阻止默认事件行为。
$('#goToGoogle').click(false);
函数handler的返回值为false,则表示阻止元素的默认事件行为,并停止事件在DOM树中冒泡。例如,\链接的click事件的处理函数返回false,可以阻止链接的默认URL跳转行为。
$('#goToGoogle').click(function(){
    return false;
});

10.平行的运行多个Ajax请求。

当我们需要发送多个Ajax请求是,相反于等待一个发送结束再发送下一个,我们可以平行地发送来加速Ajax请求发送。
// The trick is in the $.when() function:
$.when($.get('assets/misc/1.json'), $.get('assets/misc/2.json')).then(function(r1, r2){
    log(r1[0].message + " " + r2[0].message);
});

11.jQuery(使用ajax)提供了一个速记的方法来快速下载内容并添加在一个元素中。

<p class="content"></p> <p class="content"></p>
var contentDivs = $('.content');
// Fetch the contents of a text file:
contentDivs.eq(0).load('1.txt');
// Fetch the contents of a HTML file, and display a specific element:
contentDivs.eq(1).load('1.html #header');

12.JQuery扩展

jQuery.prototype = jQuery.fn = jQuery.fn.init.prototype
$.fn.abs=function(){
    console.log('abs')
}
$(document).abs();

OVER