Skip to content

Instantly share code, notes, and snippets.

@willwei
Last active December 27, 2015 03:59
Show Gist options
  • Save willwei/7263279 to your computer and use it in GitHub Desktop.
Save willwei/7263279 to your computer and use it in GitHub Desktop.
jQuery tips

##jQuery对象与DOM对象
//以下都返回了DOM对象 $("#msg")[0],$("div").eq(1)[0],$("div").get()[1],$("td")[5] //eq表示获取jquery元素;get表示获取dom元素 ##jQuery Ready $(document).ready(function(){ alert('Welcome to StarTrackr! Now no longer under police investigation!'); }); $(function() { alert('Ready to do your bidding!'); }); ##Toggling Elements (function($){ $('#clickme').click(function(){ $('#book').toggle('slow'); }); }(jQuery)); ##Add new Elements $('

A new paragraph!

').addClass('new'); $('') .insertAfter('#disclaimer'); $('').insertBefore('#disclaimer'); $('START!').prependTo('#disclaimer'); $('END!').appendTo('#disclaimer'); ##Removing Existing Elements $('#no-script').remove(); $('#celebs tr').remove(':contains("Singer")'); ##Modifying Content
$('p').html('good bye, cruel paragraphs!'); $('h2').text('All your titles are belong to us'); $('p').html('Warning! Text has been replaced … '); $('h2').text('Warning! Title elements can be …'); #Plugins ##Creating a Plugin 1.step-1
attach a function to the jQuery prototype

    //a private scope for jQuery
    (function($){
        //shell for your plugin scope
    })(jQuery);

2.step-2 separate JavaScript file named jquery.pluginname.js

//Internally $.fn is a shortcut to the jQuery.prototype
(function($) {
    // Shell for your plugin code
    $.fn.highlightOnce = function() {
    // Plugin code
    }
})(jQuery);
// Plugin code
return this.each(function() {
// Do something to each item
});

3.step-3 Adding Options && callback

(function($) {      
   // Shell for your plugin code
   $.fn.highlightOnce = function(options, callback) {
   if($.isFunction(options)) {
      callback = options;
      options = null;
    }
    options = $.extend($.fn.highlightOnce.defaults,options);
    // Plugin code
    return this.each(function() {
        // Do something to each item

        // Fire the setUp callback
        $.isFunction( options.setup ) && options.setup.call(this);
        });
        $.fn.highlightOnce.defaults = {
            color: '#fff47f',
            duration: 'fast',
            setup: null,
            complete: null
        };          
      }
    })(jQuery);

#Advanced Topics ##Extending jQuery ###Adding Methods to jQuery var SORTER = {}; SORTER.sort = function(which){ //sort the selected list } $.fn.extend({ sorter:function(){ return this.each(function(){ //sort the selected list }); } }); ###$. Prefixed Functions
(function($) { $.lapsed = function(time) { var then = new Date(Date.parse(time)); var now = new Date(); var minutes = Math.round((now-then) / 60000); var lapsed; // Determine pretty time ⋮ }; })(jQuery); ###Overwriting Existing Functionality (function($) { var _trim = $.trim; $.extend({ trim:function(text, clear) { if (clear) { return text.replace(/\s+/g,''); } return _trim.call(this, text); } }); })(jQuery); ###Create Your Own Selector $.extend($.expr[':'], { abovethefold: function(el) { return $(el).offset().top < $(window).scrollTop() + $(window).height(); } }); ##Events ###Events properties ###Custom Events $('#disclaimer').bind('do-toggle', function() { $(this).toggle('slow'); }); $('#toggleButton').click(function() { $('#disclaimer').trigger('do-toggle'); }); ###Unbinding and Namespacing $('p').unbind('mouseover');

$('p').bind('mouseover.colorize', function() {
    $(this).css('background-color', 'lemonchiffon')
})
.bind('mouseout.colorize', function() {
    $(this).css('background-color', '');
})
.click(function() {
    $(this)
    .trigger('mouseout.colorize')
    .unbind('.colorize');
});    

###Binding the iPhone: Non-standard Events ###The special Event 有些浏览器不兼容某些类型的事件,如IE6~IE8不支持hashchange事件。 这个时候可以通过jQuery自定义事件接口来模拟这个事件。 ####原理

jQuery.event.special[youEvent] = {
        /**
         * 初始化事件处理器 - this指向元素
         * @param 附加的数据
         * @param 事件类型命名空间
         * @param 回调函数
         */
        setup: function (data, namespaces, eventHandle) {
        },
        /**
         * 卸载事件处理器 - this指向元素
         * @param 事件类型命名空间
         */
        teardown: function (namespaces) {
        }
};
jQuery.event.special.multihover = {
setup: function(data, namespaces) {
// Do when the first event is bound
},
add: function(handler, data, namespaces) {
// Do every time you bind another event
},
remove: function(namespaces) {
// Do when an event is unbound
},
teardown: function(namespaces) {
// Do when the last event is unbound
},
handler: function(e) {
// Do your logic
}
}        
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment