##jQuery对象与DOM对象
//以下都返回了DOM对象
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(
$('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
}
}