You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
BookStore/web/static/script/jquery-1.7.2.js

10068 lines
320 KiB

3 years ago
/*!
* jQuery JavaScript Library v1.7.2
* http://jquery.com/
*
* Copyright 2011, John Resig
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* Includes Sizzle.js
* http://sizzlejs.com/
* Copyright 2011, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
*
* Date: Wed Mar 21 12:46:34 2012 -0700
*/
(function( window, undefined ) {
// Use the correct document accordingly with window argument (sandbox)
var document = window.document,
navigator = window.navigator,
location = window.location;
var jQuery = (function() {
// Define a local copy of jQuery
var jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// A central reference to the root jQuery(document)
rootjQuery,
// A simple way to check for HTML strings or ID strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,
// Check if a string has a non-whitespace character in it
rnotwhite = /\S/,
// Used for trimming whitespace
trimLeft = /^\s+/,
trimRight = /\s+$/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/,
// JSON RegExp
rvalidchars = /^[\],:{}\s]*$/,
rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
// Useragent RegExp
rwebkit = /(webkit)[ \/]([\w.]+)/,
ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/,
rmsie = /(msie) ([\w.]+)/,
rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/,
// Matches dashed string for camelizing
rdashAlpha = /-([a-z]|[0-9])/ig,
rmsPrefix = /^-ms-/,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return ( letter + "" ).toUpperCase();
},
// Keep a UserAgent string for use with jQuery.browser
userAgent = navigator.userAgent,
// For matching the engine and version of the browser
browserMatch,
// The deferred used on DOM ready
readyList,
// The ready event handler
DOMContentLoaded,
// Save a reference to some core methods
toString = Object.prototype.toString,
hasOwn = Object.prototype.hasOwnProperty,
push = Array.prototype.push,
slice = Array.prototype.slice,
trim = String.prototype.trim,
indexOf = Array.prototype.indexOf,
// [[Class]] -> type pairs
class2type = {};
jQuery.fn = jQuery.prototype = {
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem, ret, doc;
// Handle $(""), $(null), or $(undefined)
if ( !selector ) {
return this;
}
// Handle $(DOMElement)
if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
}
// The body element only exists once, optimize finding it
if ( selector === "body" && !context && document.body ) {
this.context = document;
this[0] = document.body;
this.selector = selector;
this.length = 1;
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
// Are we dealing with HTML string or an ID?
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = quickExpr.exec( selector );
}
// Verify a match, and that no context was specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
doc = ( context ? context.ownerDocument || context : document );
// If a single string is passed in and it's a single tag
// just do a createElement and skip the rest
ret = rsingleTag.exec( selector );
if ( ret ) {
if ( jQuery.isPlainObject( context ) ) {
selector = [ document.createElement( ret[1] ) ];
jQuery.fn.attr.call( selector, context, true );
} else {
selector = [ doc.createElement( ret[1] ) ];
}
} else {
ret = jQuery.buildFragment( [ match[1] ], [ doc ] );
selector = ( ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment ).childNodes;
}
return jQuery.merge( this, selector );
// HANDLE: $("#id")
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The current version of jQuery being used
jquery: "1.7.2",
// The default length of a jQuery object is 0
length: 0,
// The number of elements contained in the matched element set
size: function() {
return this.length;
},
toArray: function() {
return slice.call( this, 0 );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems, name, selector ) {
// Build a new jQuery matched element set
var ret = this.constructor();
if ( jQuery.isArray( elems ) ) {
push.apply( ret, elems );
} else {
jQuery.merge( ret, elems );
}
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
if ( name === "find" ) {
ret.selector = this.selector + ( this.selector ? " " : "" ) + selector;
} else if ( name ) {
ret.selector = this.selector + "." + name + "(" + selector + ")";
}
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Attach the listeners
jQuery.bindReady();
// Add the callback
readyList.add( fn );
return this;
},
eq: function( i ) {
i = +i;
return i === -1 ?
this.slice( i ) :
this.slice( i, i + 1 );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
slice: function() {
return this.pushStack( slice.apply( this, arguments ),
"slice", slice.call(arguments).join(",") );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Either a released hold or an DOMready/load event and not yet ready
if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) {
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready, 1 );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.fireWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger( "ready" ).off( "ready" );
}
}
},
bindReady: function() {
if ( readyList ) {
return;
}
readyList = jQuery.Callbacks( "once memory" );
// Catch cases where $(document).ready() is called after the
// browser event has already occurred.
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
return setTimeout( jQuery.ready, 1 );
}
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", jQuery.ready, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload,
// maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", DOMContentLoaded );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", jQuery.ready );
// If IE and not a frame
// continually check to see if the document is ready
var toplevel = false;
try {
toplevel = window.frameElement == null;
} catch(e) {}
if ( document.documentElement.doScroll && toplevel ) {
doScrollCheck();
}
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
isWindow: function( obj ) {
return obj != null && obj == obj.window;
},
isNumeric: function( obj ) {
return !isNaN( parseFloat(obj) ) && isFinite( obj );
},
type: function( obj ) {
return obj == null ?
String( obj ) :
class2type[ toString.call(obj) ] || "object";
},
isPlainObject: function( obj ) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!hasOwn.call(obj, "constructor") &&
!hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || hasOwn.call( obj, key );
},
isEmptyObject: function( obj ) {
for ( var name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw new Error( msg );
},
parseJSON: function( data ) {
if ( typeof data !== "string" || !data ) {
return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return ( new Function( "return " + data ) )();
}
jQuery.error( "Invalid JSON: " + data );
},
// Cross-browser xml parsing
parseXML: function( data ) {
if ( typeof data !== "string" || !data ) {
return null;
}
var xml, tmp;
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && rnotwhite.test( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();
},
// args is for internal usage only
each: function( object, callback, args ) {
var name, i = 0,
length = object.length,
isObj = length === undefined || jQuery.isFunction( object );
if ( args ) {
if ( isObj ) {
for ( name in object ) {
if ( callback.apply( object[ name ], args ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.apply( object[ i++ ], args ) === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isObj ) {
for ( name in object ) {
if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) {
break;
}
}
}
}
return object;
},
// Use native String.trim function wherever possible
trim: trim ?
function( text ) {
return text == null ?
"" :
trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
text.toString().replace( trimLeft, "" ).replace( trimRight, "" );
},
// results is for internal usage only
makeArray: function( array, results ) {
var ret = results || [];
if ( array != null ) {
// The window, strings (and functions) also have 'length'
// Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
var type = jQuery.type( array );
if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) {
push.call( ret, array );
} else {
jQuery.merge( ret, array );
}
}
return ret;
},
inArray: function( elem, array, i ) {
var len;
if ( array ) {
if ( indexOf ) {
return indexOf.call( array, elem, i );
}
len = array.length;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
for ( ; i < len; i++ ) {
// Skip accessing in sparse arrays
if ( i in array && array[ i ] === elem ) {
return i;
}
}
}
return -1;
},
merge: function( first, second ) {
var i = first.length,
j = 0;
if ( typeof second.length === "number" ) {
for ( var l = second.length; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var ret = [], retVal;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( var i = 0, length = elems.length; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value, key, ret = [],
i = 0,
length = elems.length,
// jquery objects are treated as arrays
isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ;
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( key in elems ) {
value = callback( elems[ key ], key, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return ret.concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
if ( typeof context === "string" ) {
var tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
var args = slice.call( arguments, 2 ),
proxy = function() {
return fn.apply( context, args.concat( slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;
return proxy;
},
// Mutifunctional method to get and set values to a collection
// The value/s can optionally be executed if it's a function
access: function( elems, fn, key, value, chainable, emptyGet, pass ) {
var exec,
bulk = key == null,
i = 0,
length = elems.length;
// Sets many values
if ( key && typeof key === "object" ) {
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], 1, emptyGet, value );
}
chainable = 1;
// Sets one value
} else if ( value !== undefined ) {
// Optionally, function values get executed if exec is true
exec = pass === undefined && jQuery.isFunction( value );
if ( bulk ) {
// Bulk operations only iterate when executing function values
if ( exec ) {
exec = fn;
fn = function( elem, key, value ) {
return exec.call( jQuery( elem ), value );
};
// Otherwise they run against the entire set
} else {
fn.call( elems, value );
fn = null;
}
}
if ( fn ) {
for (; i < length; i++ ) {
fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
}
}
chainable = 1;
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
},
now: function() {
return ( new Date() ).getTime();
},
// Use of jQuery.browser is frowned upon.
// More details: http://docs.jquery.com/Utilities/jQuery.browser
uaMatch: function( ua ) {
ua = ua.toLowerCase();
var match = rwebkit.exec( ua ) ||
ropera.exec( ua ) ||
rmsie.exec( ua ) ||
ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) ||
[];
return { browser: match[1] || "", version: match[2] || "0" };
},
sub: function() {
function jQuerySub( selector, context ) {
return new jQuerySub.fn.init( selector, context );
}
jQuery.extend( true, jQuerySub, this );
jQuerySub.superclass = this;
jQuerySub.fn = jQuerySub.prototype = this();
jQuerySub.fn.constructor = jQuerySub;
jQuerySub.sub = this.sub;
jQuerySub.fn.init = function init( selector, context ) {
if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
context = jQuerySub( context );
}
return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
};
jQuerySub.fn.init.prototype = jQuerySub.fn;
var rootjQuerySub = jQuerySub(document);
return jQuerySub;
},
browser: {}
});
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
browserMatch = jQuery.uaMatch( userAgent );
if ( browserMatch.browser ) {
jQuery.browser[ browserMatch.browser ] = true;
jQuery.browser.version = browserMatch.version;
}
// Deprecated, use jQuery.browser.webkit instead
if ( jQuery.browser.webkit ) {
jQuery.browser.safari = true;
}
// IE doesn't match non-breaking spaces with \s
if ( rnotwhite.test( "\xA0" ) ) {
trimLeft = /^[\s\xA0]+/;
trimRight = /[\s\xA0]+$/;
}
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
// Cleanup functions for the document ready method
if ( document.addEventListener ) {
DOMContentLoaded = function() {
document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
jQuery.ready();
};
} else if ( document.attachEvent ) {
DOMContentLoaded = function() {
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( document.readyState === "complete" ) {
document.detachEvent( "onreadystatechange", DOMContentLoaded );
jQuery.ready();
}
};
}
// The DOM ready check for Internet Explorer
function doScrollCheck() {
if ( jQuery.isReady ) {
return;
}
try {
// If IE is used, use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
document.documentElement.doScroll("left");
} catch(e) {
setTimeout( doScrollCheck, 1 );
return;
}
// and execute any waiting functions
jQuery.ready();
}
return jQuery;
})();
// String to Object flags format cache
var flagsCache = {};
// Convert String-formatted flags into Object-formatted ones and store in cache
function createFlags( flags ) {
var object = flagsCache[ flags ] = {},
i, length;
flags = flags.split( /\s+/ );
for ( i = 0, length = flags.length; i < length; i++ ) {
object[ flags[i] ] = true;
}
return object;
}
/*
* Create a callback list using the following parameters:
*
* flags: an optional list of space-separated flags that will change how
* the callback list behaves
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible flags:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( flags ) {
// Convert flags from String-formatted to Object-formatted
// (we check in cache first)
flags = flags ? ( flagsCache[ flags ] || createFlags( flags ) ) : {};
var // Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = [],
// Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// Flag to know if list is currently firing
firing,
// First callback to fire (used internally by add and fireWith)
firingStart,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// Add one or several callbacks to the list
add = function( args ) {
var i,
length,
elem,
type,
actual;
for ( i = 0, length = args.length; i < length; i++ ) {
elem = args[ i ];
type = jQuery.type( elem );
if ( type === "array" ) {
// Inspect recursively
add( elem );
} else if ( type === "function" ) {
// Add if not in unique mode and callback is not in
if ( !flags.unique || !self.has( elem ) ) {
list.push( elem );
}
}
}
},
// Fire callbacks
fire = function( context, args ) {
args = args || [];
memory = !flags.memory || [ context, args ];
fired = true;
firing = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( context, args ) === false && flags.stopOnFalse ) {
memory = true; // Mark as halted
break;
}
}
firing = false;
if ( list ) {
if ( !flags.once ) {
if ( stack && stack.length ) {
memory = stack.shift();
self.fireWith( memory[ 0 ], memory[ 1 ] );
}
} else if ( memory === true ) {
self.disable();
} else {
list = [];
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
var length = list.length;
add( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away, unless previous
// firing was halted (stopOnFalse)
} else if ( memory && memory !== true ) {
firingStart = length;
fire( memory[ 0 ], memory[ 1 ] );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
var args = arguments,
argIndex = 0,
argLength = args.length;
for ( ; argIndex < argLength ; argIndex++ ) {
for ( var i = 0; i < list.length; i++ ) {
if ( args[ argIndex ] === list[ i ] ) {
// Handle firingIndex and firingLength
if ( firing ) {
if ( i <= firingLength ) {
firingLength--;
if ( i <= firingIndex ) {
firingIndex--;
}
}
}
// Remove the element
list.splice( i--, 1 );
// If we have some unicity property then
// we only need to do this once
if ( flags.unique ) {
break;
}
}
}
}
}
return this;
},
// Control if a given callback is in the list
has: function( fn ) {
if ( list ) {
var i = 0,
length = list.length;
for ( ; i < length; i++ ) {
if ( fn === list[ i ] ) {
return true;
}
}
}
return false;
},
// Remove all callbacks from the list
empty: function() {
list = [];
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory || memory === true ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
if ( stack ) {
if ( firing ) {
if ( !flags.once ) {
stack.push( [ context, args ] );
}
} else if ( !( flags.once && memory ) ) {
fire( context, args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
var // Static reference to slice
sliceDeferred = [].slice;
jQuery.extend({
Deferred: function( func ) {
var doneList = jQuery.Callbacks( "once memory" ),
failList = jQuery.Callbacks( "once memory" ),
progressList = jQuery.Callbacks( "memory" ),
state = "pending",
lists = {
resolve: doneList,
reject: failList,
notify: progressList
},
promise = {
done: doneList.add,
fail: failList.add,
progress: progressList.add,
state: function() {
return state;
},
// Deprecated
isResolved: doneList.fired,
isRejected: failList.fired,
then: function( doneCallbacks, failCallbacks, progressCallbacks ) {
deferred.done( doneCallbacks ).fail( failCallbacks ).progress( progressCallbacks );
return this;
},
always: function() {
deferred.done.apply( deferred, arguments ).fail.apply( deferred, arguments );
return this;
},
pipe: function( fnDone, fnFail, fnProgress ) {
return jQuery.Deferred(function( newDefer ) {
jQuery.each( {
done: [ fnDone, "resolve" ],
fail: [ fnFail, "reject" ],
progress: [ fnProgress, "notify" ]
}, function( handler, data ) {
var fn = data[ 0 ],
action = data[ 1 ],
returned;
if ( jQuery.isFunction( fn ) ) {
deferred[ handler ](function() {
returned = fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise().then( newDefer.resolve, newDefer.reject, newDefer.notify );
} else {
newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] );
}
});
} else {
deferred[ handler ]( newDefer[ action ] );
}
});
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
if ( obj == null ) {
obj = promise;
} else {
for ( var key in promise ) {
obj[ key ] = promise[ key ];
}
}
return obj;
}
},
deferred = promise.promise({}),
key;
for ( key in lists ) {
deferred[ key ] = lists[ key ].fire;
deferred[ key + "With" ] = lists[ key ].fireWith;
}
// Handle state
deferred.done( function() {
state = "resolved";
}, failList.disable, progressList.lock ).fail( function() {
state = "rejected";
}, doneList.disable, progressList.lock );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( firstParam ) {
var args = sliceDeferred.call( arguments, 0 ),
i = 0,
length = args.length,
pValues = new Array( length ),
count = length,
pCount = length,
deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ?
firstParam :
jQuery.Deferred(),
promise = deferred.promise();
function resolveFunc( i ) {
return function( value ) {
args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value;
if ( !( --count ) ) {
deferred.resolveWith( deferred, args );
}
};
}
function progressFunc( i ) {
return function( value ) {
pValues[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value;
deferred.notifyWith( promise, pValues );
};
}
if ( length > 1 ) {
for ( ; i < length; i++ ) {
if ( args[ i ] && args[ i ].promise && jQuery.isFunction( args[ i ].promise ) ) {
args[ i ].promise().then( resolveFunc(i), deferred.reject, progressFunc(i) );
} else {
--count;
}
}
if ( !count ) {
deferred.resolveWith( deferred, args );
}
} else if ( deferred !== firstParam ) {
deferred.resolveWith( deferred, length ? [ firstParam ] : [] );
}
return promise;
}
});
jQuery.support = (function() {
var support,
all,
a,
select,
opt,
input,
fragment,
tds,
events,
eventName,
i,
isSupported,
div = document.createElement( "div" ),
documentElement = document.documentElement;
// Preliminary tests
div.setAttribute("className", "t");
div.innerHTML = " <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>";
all = div.getElementsByTagName( "*" );
a = div.getElementsByTagName( "a" )[ 0 ];
// Can't get basic test support
if ( !all || !all.length || !a ) {
return {};
}
// First batch of supports tests
select = document.createElement( "select" );
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName( "input" )[ 0 ];
support = {
// IE strips leading whitespace when .innerHTML is used
leadingWhitespace: ( div.firstChild.nodeType === 3 ),
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
tbody: !div.getElementsByTagName("tbody").length,
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
htmlSerialize: !!div.getElementsByTagName("link").length,
// Get the style information from getAttribute
// (IE uses .cssText instead)
style: /top/.test( a.getAttribute("style") ),
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
hrefNormalized: ( a.getAttribute("href") === "/a" ),
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
opacity: /^0.55/.test( a.style.opacity ),
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
cssFloat: !!a.style.cssFloat,
// Make sure that if no value is specified for a checkbox
// that it defaults to "on".
// (WebKit defaults to "" instead)
checkOn: ( input.value === "on" ),
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
optSelected: opt.selected,
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
getSetAttribute: div.className !== "t",
// Tests for enctype support on a form(#6743)
enctype: !!document.createElement("form").enctype,
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>",
// Will be defined later
submitBubbles: true,
changeBubbles: true,
focusinBubbles: false,
deleteExpando: true,
noCloneEvent: true,
inlineBlockNeedsLayout: false,
shrinkWrapBlocks: false,
reliableMarginRight: true,
pixelMargin: true
};
// jQuery.boxModel DEPRECATED in 1.3, use jQuery.support.boxModel instead
jQuery.boxModel = support.boxModel = (document.compatMode === "CSS1Compat");
// Make sure checked status is properly cloned
input.checked = true;
support.noCloneChecked = input.cloneNode( true ).checked;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Test to see if it's possible to delete an expando from an element
// Fails in Internet Explorer
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
if ( !div.addEventListener && div.attachEvent && div.fireEvent ) {
div.attachEvent( "onclick", function() {
// Cloning a node shouldn't copy over any
// bound event handlers (IE does this)
support.noCloneEvent = false;
});
div.cloneNode( true ).fireEvent( "onclick" );
}
// Check if a radio maintains its value
// after being appended to the DOM
input = document.createElement("input");
input.value = "t";
input.setAttribute("type", "radio");
support.radioValue = input.value === "t";
input.setAttribute("checked", "checked");
// #11217 - WebKit loses check when the name is after the checked attribute
input.setAttribute( "name", "t" );
div.appendChild( input );
fragment = document.createDocumentFragment();
fragment.appendChild( div.lastChild );
// WebKit doesn't clone checked state correctly in fragments
support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
support.appendChecked = input.checked;
fragment.removeChild( input );
fragment.appendChild( div );
// Technique from Juriy Zaytsev
// http://perfectionkills.com/detecting-event-support-without-browser-sniffing/
// We only care about the case where non-standard event systems
// are used, namely in IE. Short-circuiting here helps us to
// avoid an eval call (in setAttribute) which can cause CSP
// to go haywire. See: https://developer.mozilla.org/en/Security/CSP
if ( div.attachEvent ) {
for ( i in {
submit: 1,
change: 1,
focusin: 1
}) {
eventName = "on" + i;
isSupported = ( eventName in div );
if ( !isSupported ) {
div.setAttribute( eventName, "return;" );
isSupported = ( typeof div[ eventName ] === "function" );
}
support[ i + "Bubbles" ] = isSupported;
}
}
fragment.removeChild( div );
// Null elements to avoid leaks in IE
fragment = select = opt = div = input = null;
// Run tests that need a body at doc ready
jQuery(function() {
var container, outer, inner, table, td, offsetSupport,
marginDiv, conMarginTop, style, html, positionTopLeftWidthHeight,
paddingMarginBorderVisibility, paddingMarginBorder,
body = document.getElementsByTagName("body")[0];
if ( !body ) {
// Return for frameset docs that don't have a body
return;
}
conMarginTop = 1;
paddingMarginBorder = "padding:0;margin:0;border:";
positionTopLeftWidthHeight = "position:absolute;top:0;left:0;width:1px;height:1px;";
paddingMarginBorderVisibility = paddingMarginBorder + "0;visibility:hidden;";
style = "style='" + positionTopLeftWidthHeight + paddingMarginBorder + "5px solid #000;";
html = "<div " + style + "display:block;'><div style='" + paddingMarginBorder + "0;display:block;overflow:hidden;'></div></div>" +
"<table " + style + "' cellpadding='0' cellspacing='0'>" +
"<tr><td></td></tr></table>";
container = document.createElement("div");
container.style.cssText = paddingMarginBorderVisibility + "width:0;height:0;position:static;top:0;margin-top:" + conMarginTop + "px";
body.insertBefore( container, body.firstChild );
// Construct the test element
div = document.createElement("div");
container.appendChild( div );
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
// (only IE 8 fails this test)
div.innerHTML = "<table><tr><td style='" + paddingMarginBorder + "0;display:none'></td><td>t</td></tr></table>";
tds = div.getElementsByTagName( "td" );
isSupported = ( tds[ 0 ].offsetHeight === 0 );
tds[ 0 ].style.display = "";
tds[ 1 ].style.display = "none";
// Check if empty table cells still have offsetWidth/Height
// (IE <= 8 fail this test)
support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. For more
// info see bug #3333
// Fails in WebKit before Feb 2011 nightlies
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
if ( window.getComputedStyle ) {
div.innerHTML = "";
marginDiv = document.createElement( "div" );
marginDiv.style.width = "0";
marginDiv.style.marginRight = "0";
div.style.width = "2px";
div.appendChild( marginDiv );
support.reliableMarginRight =
( parseInt( ( window.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0;
}
if ( typeof div.style.zoom !== "undefined" ) {
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
// (IE < 8 does this)
div.innerHTML = "";
div.style.width = div.style.padding = "1px";
div.style.border = 0;
div.style.overflow = "hidden";
div.style.display = "inline";
div.style.zoom = 1;
support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 );
// Check if elements with layout shrink-wrap their children
// (IE 6 does this)
div.style.display = "block";
div.style.overflow = "visible";
div.innerHTML = "<div style='width:5px;'></div>";
support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );
}
div.style.cssText = positionTopLeftWidthHeight + paddingMarginBorderVisibility;
div.innerHTML = html;
outer = div.firstChild;
inner = outer.firstChild;
td = outer.nextSibling.firstChild.firstChild;
offsetSupport = {
doesNotAddBorder: ( inner.offsetTop !== 5 ),
doesAddBorderForTableAndCells: ( td.offsetTop === 5 )
};
inner.style.position = "fixed";
inner.style.top = "20px";
// safari subtracts parent border width here which is 5px
offsetSupport.fixedPosition = ( inner.offsetTop === 20 || inner.offsetTop === 15 );
inner.style.position = inner.style.top = "";
outer.style.overflow = "hidden";
outer.style.position = "relative";
offsetSupport.subtractsBorderForOverflowNotVisible = ( inner.offsetTop === -5 );
offsetSupport.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== conMarginTop );
if ( window.getComputedStyle ) {
div.style.marginTop = "1%";
support.pixelMargin = ( window.getComputedStyle( div, null ) || { marginTop: 0 } ).marginTop !== "1%";
}
if ( typeof container.style.zoom !== "undefined" ) {
container.style.zoom = 1;
}
body.removeChild( container );
marginDiv = div = container = null;
jQuery.extend( support, offsetSupport );
});
return support;
})();
var rbrace = /^(?:\{.*\}|\[.*\])$/,
rmultiDash = /([A-Z])/g;
jQuery.extend({
cache: {},
// Please use with caution
uuid: 0,
// Unique for each copy of jQuery on the page
// Non-digits removed to match rinlinejQuery
expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ),
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
noData: {
"embed": true,
// Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
"applet": true
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var privateCache, thisCache, ret,
internalKey = jQuery.expando,
getByName = typeof name === "string",
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey,
isEvents = name === "events";
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( (!id || !cache[id] || (!isEvents && !pvt && !cache[id].data)) && getByName && data === undefined ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
elem[ internalKey ] = id = ++jQuery.uuid;
} else {
id = internalKey;
}
}
if ( !cache[ id ] ) {
cache[ id ] = {};
// Avoids exposing jQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
if ( !isNode ) {
cache[ id ].toJSON = jQuery.noop;
}
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ] = jQuery.extend( cache[ id ], name );
} else {
cache[ id ].data = jQuery.extend( cache[ id ].data, name );
}
}
privateCache = thisCache = cache[ id ];
// jQuery data() is stored in a separate object inside the object's internal data
// cache in order to avoid key collisions between internal data and user-defined
// data.
if ( !pvt ) {
if ( !thisCache.data ) {
thisCache.data = {};
}
thisCache = thisCache.data;
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// Users should not attempt to inspect the internal events object using jQuery.data,
// it is undocumented and subject to change. But does anyone listen? No.
if ( isEvents && !thisCache[ name ] ) {
return privateCache.events;
}
// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if ( getByName ) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if ( ret == null ) {
// Try to find the camelCased property
ret = thisCache[ jQuery.camelCase( name ) ];
}
} else {
ret = thisCache;
}
return ret;
},
removeData: function( elem, name, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, i, l,
// Reference to internal data cache key
internalKey = jQuery.expando,
isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
// See jQuery.data for more information
id = isNode ? elem[ internalKey ] : internalKey;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
thisCache = pvt ? cache[ id ] : cache[ id ].data;
if ( thisCache ) {
// Support array or space separated string names for data keys
if ( !jQuery.isArray( name ) ) {
// try the string as a key before any manipulation
if ( name in thisCache ) {
name = [ name ];
} else {
// split the camel cased version by spaces unless a key with the spaces exists
name = jQuery.camelCase( name );
if ( name in thisCache ) {
name = [ name ];
} else {
name = name.split( " " );
}
}
}
for ( i = 0, l = name.length; i < l; i++ ) {
delete thisCache[ name[i] ];
}
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) {
return;
}
}
}
// See jQuery.data for more information
if ( !pvt ) {
delete cache[ id ].data;
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject(cache[ id ]) ) {
return;
}
}
// Browsers that fail expando deletion also refuse to delete expandos on
// the window, but it will allow it on all other JS objects; other browsers
// don't care
// Ensure that `cache` is not a window object #10080
if ( jQuery.support.deleteExpando || !cache.setInterval ) {
delete cache[ id ];
} else {
cache[ id ] = null;
}
// We destroyed the cache and need to eliminate the expando on the node to avoid
// false lookups in the cache for entries that no longer exist
if ( isNode ) {
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( jQuery.support.deleteExpando ) {
delete elem[ internalKey ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = null;
}
}
},
// For internal use only.
_data: function( elem, name, data ) {
return jQuery.data( elem, name, data, true );
},
// A method for determining if a DOM node can handle the data expando
acceptData: function( elem ) {
if ( elem.nodeName ) {
var match = jQuery.noData[ elem.nodeName.toLowerCase() ];
if ( match ) {
return !(match === true || elem.getAttribute("classid") !== match);
}
}
return true;
}
});
jQuery.fn.extend({
data: function( key, value ) {
var parts, part, attr, name, l,
elem = this[0],
i = 0,
data = null;
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = jQuery.data( elem );
if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
attr = elem.attributes;
for ( l = attr.length; i < l; i++ ) {
name = attr[i].name;
if ( name.indexOf( "data-" ) === 0 ) {
name = jQuery.camelCase( name.substring(5) );
dataAttr( elem, name, data[ name ] );
}
}
jQuery._data( elem, "parsedAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
parts = key.split( ".", 2 );
parts[1] = parts[1] ? "." + parts[1] : "";
part = parts[1] + "!";
return jQuery.access( this, function( value ) {
if ( value === undefined ) {
data = this.triggerHandler( "getData" + part, [ parts[0] ] );
// Try to fetch any internally stored data first
if ( data === undefined && elem ) {
data = jQuery.data( elem, key );
data = dataAttr( elem, key, data );
}
return data === undefined && parts[1] ?
this.data( parts[0] ) :
data;
}
parts[1] = value;
this.each(function() {
var self = jQuery( this );
self.triggerHandler( "setData" + part, parts );
jQuery.data( this, key, value );
self.triggerHandler( "changeData" + part, parts );
});
}, null, value, arguments.length > 1, null, false );
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
jQuery.isNumeric( data ) ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
for ( var name in obj ) {
// if the public data object is empty, the private is still empty
if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
continue;
}
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
function handleQueueMarkDefer( elem, type, src ) {
var deferDataKey = type + "defer",
queueDataKey = type + "queue",
markDataKey = type + "mark",
defer = jQuery._data( elem, deferDataKey );
if ( defer &&
( src === "queue" || !jQuery._data(elem, queueDataKey) ) &&
( src === "mark" || !jQuery._data(elem, markDataKey) ) ) {
// Give room for hard-coded callbacks to fire first
// and eventually mark/queue something else on the element
setTimeout( function() {
if ( !jQuery._data( elem, queueDataKey ) &&
!jQuery._data( elem, markDataKey ) ) {
jQuery.removeData( elem, deferDataKey, true );
defer.fire();
}
}, 0 );
}
}
jQuery.extend({
_mark: function( elem, type ) {
if ( elem ) {
type = ( type || "fx" ) + "mark";
jQuery._data( elem, type, (jQuery._data( elem, type ) || 0) + 1 );
}
},
_unmark: function( force, elem, type ) {
if ( force !== true ) {
type = elem;
elem = force;
force = false;
}
if ( elem ) {
type = type || "fx";
var key = type + "mark",
count = force ? 0 : ( (jQuery._data( elem, key ) || 1) - 1 );
if ( count ) {
jQuery._data( elem, key, count );
} else {
jQuery.removeData( elem, key, true );
handleQueueMarkDefer( elem, type, "mark" );
}
}
},
queue: function( elem, type, data ) {
var q;
if ( elem ) {
type = ( type || "fx" ) + "queue";
q = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !q || jQuery.isArray(data) ) {
q = jQuery._data( elem, type, jQuery.makeArray(data) );
} else {
q.push( data );
}
}
return q || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
fn = queue.shift(),
hooks = {};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
jQuery._data( elem, type + ".run", hooks );
fn.call( elem, function() {
jQuery.dequeue( elem, type );
}, hooks );
}
if ( !queue.length ) {
jQuery.removeData( elem, type + "queue " + type + ".run", true );
handleQueueMarkDefer( elem, type, "queue" );
}
}
});
4 weeks ago
// 扩展jQuery对象的函数
jQuery.fn.extend({
// queue函数用于处理元素队列
queue: function( type, data ) {
var setter = 2;
3 years ago
4 weeks ago
// 如果type不是字符串则将data和type的值互换并将setter减1
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
3 years ago
4 weeks ago
// 如果参数不足setter个数则返回指定元素的队列
if ( arguments.length < setter ) {
return jQuery.queue( this[0], type );
}
3 years ago
4 weeks ago
// 如果data未定义则直接返回this否则遍历每个元素
return data === undefined ?
this :
this.each(function() {
var queue = jQuery.queue( this, type, data );
3 years ago
4 weeks ago
// 如果type是"fx"且队列的第一个元素不是"inprogress"则执行dequeue
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
// dequeue函数用于从队列中移除下一个待执行的函数
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
3 years ago
});
4 weeks ago
},
// delay函数用于在队列中添加一个延时函数
delay: function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
3 years ago
4 weeks ago
// 在队列中添加一个延时函数
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
},
// clearQueue函数用于清空指定类型的队列
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// promise函数用于获取一个在队列清空时解决的承诺
promise: function( type, object ) {
if ( typeof type !== "string" ) {
object = type;
type = undefined;
3 years ago
}
4 weeks ago
type = type || "fx";
var defer = jQuery.Deferred(),
elements = this,
i = elements.length,
count = 1,
deferDataKey = type + "defer",
queueDataKey = type + "queue",
markDataKey = type + "mark",
tmp;
function resolve() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
}
while( i-- ) {
if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) ||
3 years ago
( jQuery.data( elements[ i ], queueDataKey, undefined, true ) ||
jQuery.data( elements[ i ], markDataKey, undefined, true ) ) &&
jQuery.data( elements[ i ], deferDataKey, jQuery.Callbacks( "once memory" ), true ) )) {
4 weeks ago
count++;
tmp.add( resolve );
}
3 years ago
}
4 weeks ago
resolve();
return defer.promise( object );
3 years ago
}
4 weeks ago
});
3 years ago
4 weeks ago
// 正则表达式,用于去除字符串中的换行、制表符和回车符
var rclass = /[\n\t\r]/g,
// 正则表达式,用于匹配一个或多个空格
rspace = /\s+/,
// 正则表达式,用于匹配回车符
rreturn = /\r/g,
// 正则表达式用于匹配button或input元素
rtype = /^(?:button|input)$/i,
// 正则表达式用于匹配button、input、object、select或textarea元素
rfocusable = /^(?:button|input|object|select|textarea)$/i,
// 正则表达式用于匹配a或area元素
rclickable = /^a(?:rea)?$/i,
// 正则表达式,用于匹配布尔属性
rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,
// 检查是否支持getAttribute和setAttribute
getSetAttribute = jQuery.support.getSetAttribute,
nodeHook, boolHook, fixSpecified;
// 扩展jQuery对象的函数用于属性和属性值的操作
jQuery.fn.extend({
// attr函数用于获取或设置元素的属性值
attr: function( name, value ) {
return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );
},
// removeAttr函数用于移除元素的属性
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
3 years ago
});
4 weeks ago
},
// prop函数用于获取或设置元素的属性值适用于标准属性
prop: function( name, value ) {
return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 );
},
// removeProp函数用于移除元素的属性适用于标准属性
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each(function() {
// try/catch处理IE浏览器中删除属性时可能抛出的异常
try {
this[ name ] = undefined;
delete this[ name ];
} catch( e ) {}
});
},
// addClass函数用于给元素添加类名
addClass: function( value ) {
var classNames, i, l, elem,
setClass, c, cl;
// 如果value是函数则为每个元素调用该函数并添加返回的类名
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call(this, j, this.className) );
});
}
3 years ago
4 weeks ago
// 如果value是字符串则按空格分割类名并为每个元素添加这些类名
if ( value && typeof value === "string" ) {
classNames = value.split( rspace );
3 years ago
4 weeks ago
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
3 years ago
4 weeks ago
// 如果元素是元素节点且没有类名,则直接设置类名
if ( elem.nodeType === 1 ) {
if ( !elem.className && classNames.length === 1 ) {
elem.className = value;
3 years ago
4 weeks ago
} else {
// 如果元素已经有类名,则在已有类名基础上添加新类名
setClass = " " + elem.className + " ";
3 years ago
4 weeks ago
for ( c = 0, cl = classNames.length; c < cl; c++ ) {
if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) {
setClass += classNames[ c ] + " ";
}
3 years ago
}
4 weeks ago
elem.className = jQuery.trim( setClass );
3 years ago
}
}
}
}
4 weeks ago
// 返回this以支持链式调用
return this;
},
// removeClass函数用于从元素中移除类名
removeClass: function( value ) {
var classNames, i, l, elem, className, c, cl;
// 如果value是函数则为每个元素调用该函数并移除返回的类名
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call(this, j, this.className) );
});
}
3 years ago
4 weeks ago
// 如果value是字符串或undefined则按空格分割类名并为每个元素移除这些类名
if ( (value && typeof value === "string") || value === undefined ) {
classNames = ( value || "" ).split( rspace );
3 years ago
4 weeks ago
// 遍历每个元素,对每个元素执行以下操作
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ]; // 获取当前遍历的元素
3 years ago
4 weeks ago
// 如果元素是元素节点并且有类名
if ( elem.nodeType === 1 && elem.className ) {
if ( value ) {
// 如果value存在则创建一个包含当前类名和新类名的字符串
className = (" " + elem.className + " ").replace( rclass, " " );
// 遍历所有要移除的类名
for ( c = 0, cl = classNames.length; c < cl; c++ ) {
// 移除类名
className = className.replace(" " + classNames[ c ] + " ", " ");
}
// 更新元素的类名
elem.className = jQuery.trim( className );
3 years ago
4 weeks ago
} else {
// 如果value不存在则清空元素的类名
elem.className = "";
3 years ago
}
}
}
4 weeks ago
// 返回this以支持链式调用
return this;
},
3 years ago
4 weeks ago
// toggleClass函数用于根据条件切换元素的类名
toggleClass: function( value, stateVal ) {
var type = typeof value,
isBool = typeof stateVal === "boolean";
3 years ago
4 weeks ago
// 如果value是函数则对每个元素执行该函数并根据返回值切换类名
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
3 years ago
}
4 weeks ago
// 对每个元素执行类名切换操作
return this.each(function() {
if ( type === "string" ) {
// 切换单个类名
var className,
i = 0,
self = jQuery( this ),
state = stateVal,
classNames = value.split( rspace );
while ( (className = classNames[ i++ ]) ) {
// 检查每个给定的类名,空格分隔的列表
state = isBool ? state : !self.hasClass( className );
self[ state ? "addClass" : "removeClass" ]( className );
}
3 years ago
4 weeks ago
} else if ( type === "undefined" || type === "boolean" ) {
if ( this.className ) {
// 如果设置了类名,则存储类名
jQuery._data( this, "__className__", this.className );
}
3 years ago
4 weeks ago
// 切换整个类名
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
3 years ago
4 weeks ago
// hasClass函数用于检查元素是否包含指定的类名
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) {
return true;
}
3 years ago
}
4 weeks ago
return false;
},
3 years ago
4 weeks ago
// val函数用于获取或设置表单元素的值
val: function( value ) {
var hooks, ret, isFunction,
elem = this[0];
3 years ago
4 weeks ago
// 如果没有参数,则获取第一个元素的值
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
3 years ago
4 weeks ago
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
3 years ago
4 weeks ago
ret = elem.value;
3 years ago
4 weeks ago
return typeof ret === "string" ?
// 处理最常见的字符串情况
ret.replace(rreturn, "") :
// 处理值是null/undef或数字的情况
ret == null ? "" : ret;
}
3 years ago
4 weeks ago
return;
3 years ago
}
4 weeks ago
isFunction = jQuery.isFunction( value );
3 years ago
4 weeks ago
// 对每个元素执行值设置操作
return this.each(function( i ) {
var self = jQuery(this), val;
3 years ago
4 weeks ago
if ( this.nodeType !== 1 ) {
return;
3 years ago
}
4 weeks ago
if ( isFunction ) {
val = value.call( this, i, self.val() );
} else {
val = value;
}
3 years ago
4 weeks ago
// 将null/undefined视为"";将数字转换为字符串
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map(val, function ( value ) {
return value == null ? "" : value + "";
});
}
3 years ago
4 weeks ago
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
3 years ago
4 weeks ago
// 如果set返回undefined则回退到正常设置
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
3 years ago
});
}
4 weeks ago
jQuery.extend({
valHooks: {
// option元素的值钩子
option: {
get: function( elem ) {
// 在Blackberry 4.7中attributes.value是undefined但使用.value
var val = elem.attributes.value;
return !val || val.specified ? elem.value : elem.text;
}
},
// select元素的值钩子
select: {
get: function( elem ) {
var value, i, max, option,
index = elem.selectedIndex,
values = [],
options = elem.options,
one = elem.type === "select-one";
// 没有选中任何选项
if ( index < 0 ) {
return null;
}
3 years ago
4 weeks ago
// 遍历所有选中的选项
i = one ? index : 0;
max = one ? index + 1 : options.length;
for ( ; i < max; i++ ) {
option = options[ i ];
3 years ago
4 weeks ago
// 不返回禁用的选项或在禁用的optgroup中的选项
if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) &&
(!(option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) ) {
3 years ago
4 weeks ago
// 获取选项的特定值
value = jQuery( option ).val();
3 years ago
4 weeks ago
// 单选不需要数组
if ( one ) {
return value;
}
3 years ago
4 weeks ago
// 多选返回数组
values.push( value );
}
}
3 years ago
4 weeks ago
// 修复Bug #2551 -- 在表单重置后select.val()在IE中被破坏
if ( one && !values.length && options.length ) {
return jQuery( options[ index ] ).val();
}
3 years ago
4 weeks ago
return values;
},
3 years ago
4 weeks ago
set: function( elem, value ) {
var values = jQuery.makeArray( value );
3 years ago
4 weeks ago
jQuery(elem).find("option").each(function() {
this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
});
3 years ago
4 weeks ago
if ( !values.length ) {
elem.selectedIndex = -1;
}
return values;
}
}
},
3 years ago
4 weeks ago
// 定义一个对象包含那些可以通过jQuery.attr和jQuery.prop直接访问的属性和方法
attrFn: {
val: true, // 值属性
css: true, // CSS样式
html: true, // 内部HTML
text: true, // 文本内容
data: true, // 数据属性
width: true, // 宽度
height: true, // 高度
offset: true // 偏移位置
},
3 years ago
4 weeks ago
// attr函数用于获取或设置元素的属性值
attr: function( elem, name, value, pass ) {
var ret, hooks, notxml,
nType = elem.nodeType;
3 years ago
4 weeks ago
// 不对文本、注释和属性节点进行属性的获取和设置
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
3 years ago
}
4 weeks ago
if ( pass && name in jQuery.attrFn ) {
return jQuery( elem )[ name ]( value );
3 years ago
}
4 weeks ago
// 当元素不支持属性时回退到prop
if ( typeof elem.getAttribute === "undefined" ) {
return jQuery.prop( elem, name, value );
3 years ago
}
4 weeks ago
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
3 years ago
4 weeks ago
// 所有属性都转换为小写
// 如果定义了必要的钩子,则获取它
if ( notxml ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook );
3 years ago
}
4 weeks ago
if ( value !== undefined ) {
3 years ago
4 weeks ago
if ( value === null ) {
jQuery.removeAttr( elem, name );
} else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, "" + value );
return value;
}
3 years ago
4 weeks ago
} else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) {
return ret;
3 years ago
4 weeks ago
} else {
3 years ago
4 weeks ago
ret = elem.getAttribute( name );
3 years ago
4 weeks ago
// 非存在的属性返回null我们将其标准化为undefined
return ret === null ?
undefined :
ret;
}
},
3 years ago
4 weeks ago
// removeAttr函数用于移除元素的一个或多个属性
removeAttr: function( elem, value ) {
var propName, attrNames, name, l, isBool,
i = 0;
3 years ago
4 weeks ago
if ( value && elem.nodeType === 1 ) {
attrNames = value.toLowerCase().split( rspace );
l = attrNames.length;
3 years ago
4 weeks ago
for ( ; i < l; i++ ) {
name = attrNames[ i ];
3 years ago
4 weeks ago
if ( name ) {
propName = jQuery.propFix[ name ] || name;
isBool = rboolean.test( name );
3 years ago
4 weeks ago
// 见#9699的解释先设置然后移除
// 对于布尔属性不要这样做(见#10870
if ( !isBool ) {
jQuery.attr( elem, name, "" );
}
elem.removeAttribute( getSetAttribute ? name : propName );
3 years ago
4 weeks ago
// 对于布尔属性将对应的属性设置为false
if ( isBool && propName in elem ) {
elem[ propName ] = false;
}
}
}
}
},
3 years ago
4 weeks ago
// attrHooks对象包含特定属性的获取和设置钩子
attrHooks: {
type: {
set: function( elem, value ) {
// 我们不允许改变type属性因为这在IE中会导致问题
if ( rtype.test( elem.nodeName ) && elem.parentNode ) {
jQuery.error( "type property can't be changed" );
} else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// 在IE6-9中设置radio按钮的type属性后value会重置
// 如果type属性在value属性之后设置则重置value为其默认值
// 这是为了元素创建
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
},
// 为了向后兼容使用value属性
// 在IE6/7中使用nodeHook处理按钮元素#1954
value: {
get: function( elem, name ) {
if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
return nodeHook.get( elem, name );
}
return name in elem ?
elem.value :
null;
},
set: function( elem, value, name ) {
if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
return nodeHook.set( elem, value, name );
}
// 不返回以便也使用setAttribute
elem.value = value;
}
}
},
3 years ago
4 weeks ago
// propFix对象包含属性名的修正
propFix: {
tabindex: "tabIndex",
readonly: "readOnly",
"for": "htmlFor",
"class": "className",
maxlength: "maxLength",
cellspacing: "cellSpacing",
cellpadding: "cellPadding",
rowspan: "rowSpan",
colspan: "colSpan",
usemap: "useMap",
frameborder: "frameBorder",
contenteditable: "contentEditable"
},
3 years ago
4 weeks ago
// prop函数用于获取或设置元素的标准属性值
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
3 years ago
4 weeks ago
// 不对文本、注释和属性节点进行属性的获取和设置
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
3 years ago
4 weeks ago
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
3 years ago
4 weeks ago
if ( notxml ) {
// 修正名称并附加钩子
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
3 years ago
4 weeks ago
if ( value !== undefined ) {
if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
3 years ago
4 weeks ago
} else {
return ( elem[ name ] = value );
}
3 years ago
4 weeks ago
} else {
if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
3 years ago
4 weeks ago
} else {
return elem[ name ];
}
}
},
3 years ago
4 weeks ago
// propHooks对象包含特定属性的获取和设置钩子
propHooks: {
tabIndex: {
get: function( elem ) {
// elem.tabIndex并不总是返回正确的值当它没有被显式设置时
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
var attributeNode = elem.getAttributeNode("tabindex");
return attributeNode && attributeNode.specified ?
parseInt( attributeNode.value, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
undefined;
}
}
3 years ago
}
4 weeks ago
});
// Add the tabIndex propHook to attrHooks for back-compat (different case is intentional)
jQuery.attrHooks.tabindex = jQuery.propHooks.tabIndex;
3 years ago
4 weeks ago
// Hook for boolean attributes
// 定义布尔属性的获取和设置钩子
boolHook = {
get: function( elem, name ) {
// 将布尔属性与相应的属性对齐
// 在一些布尔属性不受支持的地方,回退到属性存在性检查
var attrNode,
property = jQuery.prop( elem, name );
return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ?
name.toLowerCase() :
undefined;
},
set: function( elem, value, name ) {
var propName;
if ( value === false ) {
// 当设置为false时移除布尔属性
jQuery.removeAttr( elem, name );
} else {
// 我们知道此时value为true因为它是布尔类型且不是false
// 设置布尔属性为相同名称并设置DOM属性
propName = jQuery.propFix[ name ] || name;
if ( propName in elem ) {
// 仅当IDL已经存在于元素上时才设置IDL
elem[ propName ] = true;
}
3 years ago
4 weeks ago
elem.setAttribute( name, name.toLowerCase() );
}
return name;
3 years ago
}
4 weeks ago
};
3 years ago
4 weeks ago
// IE6/7不支持通过get/setAttribute获取/设置某些属性
if ( !getSetAttribute ) {
fixSpecified = {
name: true,
id: true,
coords: true
};
// 用于IE6/7中的任何属性
// 这几乎修复了所有IE6/7的问题
nodeHook = jQuery.valHooks.button = {
get: function( elem, name ) {
var ret;
ret = elem.getAttributeNode( name );
return ret && ( fixSpecified[ name ] ? ret.nodeValue !== "" : ret.specified ) ?
ret.nodeValue :
undefined;
},
set: function( elem, value, name ) {
// 设置现有的或创建一个新的属性节点
var ret = elem.getAttributeNode( name );
if ( !ret ) {
ret = document.createAttribute( name );
elem.setAttributeNode( ret );
}
return ( ret.nodeValue = value + "" );
}
};
// 将nodeHook应用于tabindex
jQuery.attrHooks.tabindex.set = nodeHook.set;
// 在空字符串时将width和height设置为auto而不是0Bug #8150
// 这是为了移除操作
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
});
});
3 years ago
4 weeks ago
// 在移除时将contenteditable设置为false#10429
// 设置为空字符串会因为无效值而抛出错误
jQuery.attrHooks.contenteditable = {
get: nodeHook.get,
set: function( elem, value, name ) {
if ( value === "" ) {
value = "false";
}
nodeHook.set( elem, value, name );
}
};
3 years ago
}
4 weeks ago
// IE不支持href属性的规范化
if ( !jQuery.support.hrefNormalized ) {
jQuery.each([ "href", "src", "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
get: function( elem ) {
var ret = elem.getAttribute( name, 2 );
return ret === null ? undefined : ret;
}
});
});
}
3 years ago
4 weeks ago
// IE不支持style属性
if ( !jQuery.support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// 在空字符串的情况下返回undefined
// 将IE中的css属性名统一为小写
return elem.style.cssText.toLowerCase() || undefined;
},
set: function( elem, value ) {
return ( elem.style.cssText = "" + value );
}
};
}
3 years ago
4 weeks ago
// Safari错误地报告了option的默认selected属性
// 访问父元素的selectedIndex属性可以修复它
if ( !jQuery.support.optSelected ) {
jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, {
get: function( elem ) {
var parent = elem.parentNode;
3 years ago
4 weeks ago
if ( parent ) {
parent.selectedIndex;
3 years ago
4 weeks ago
// 确保这也适用于optgroup见#5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
return null;
}
});
}
3 years ago
4 weeks ago
// IE6/7调用enctype编码
if ( !jQuery.support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
3 years ago
4 weeks ago
// 单选按钮和复选框的获取/设置
if ( !jQuery.support.checkOn ) {
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
get: function( elem ) {
// 处理Webkit返回""而不是"on"的情况,如果没有指定值
return elem.getAttribute("value") === null ? "on" : elem.value;
}
};
});
}
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
});
});
3 years ago
4 weeks ago
// 定义用于匹配表单元素的正则表达式
var rformElems = /^(?:textarea|input|select)$/i,
// 定义用于匹配命名空间的正则表达式
rtypenamespace = /^([^\.]*)?(?:\.(.+))?$/,
// 定义用于处理hover事件hack的正则表达式
rhoverHack = /(?:^|\s)hover(\.\S+)?\b/,
// 定义用于匹配键盘事件的正则表达式
rkeyEvent = /^key/,
// 定义用于匹配鼠标事件的正则表达式
rmouseEvent = /^(?:mouse|contextmenu)|click/,
// 定义用于匹配focus事件的正则表达式
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
// 定义用于快速解析选择器的正则表达式
rquickIs = /^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,
// 快速解析选择器的辅助函数
quickParse = function( selector ) {
var quick = rquickIs.exec( selector );
if ( quick ) {
// 0 1 2 3
// [ _, tag, id, class ]
quick[1] = ( quick[1] || "" ).toLowerCase();
quick[3] = quick[3] && new RegExp( "(?:^|\\s)" + quick[3] + "(?:\\s|$)" );
}
return quick;
},
// 快速检查元素是否匹配选择器的函数
quickIs = function( elem, m ) {
var attrs = elem.attributes || {};
return (
(!m[1] || elem.nodeName.toLowerCase() === m[1]) &&
(!m[2] || (attrs.id || {}).value === m[2]) &&
(!m[3] || m[3].test( (attrs[ "class" ] || {}).value ))
);
},
// 处理hover事件hack的函数
hoverHack = function( events ) {
return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" );
};
/*
* 事件管理的帮助函数不是公共接口的一部分
* 许多想法来自Dean Edwards' addEvent库
*/
jQuery.event = {
add: function( elem, types, handler, data, selector ) {
var elemData, eventHandle, events,
t, tns, type, namespaces, handleObj,
handleObjIn, quick, handlers, special;
// 不要为noData或文本/注释节点附加事件(允许纯对象)
if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) {
return;
}
3 years ago
4 weeks ago
// 调用者可以传入一个自定义数据对象代替处理器
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
3 years ago
4 weeks ago
// 确保处理器有一个唯一的ID用于稍后查找/移除它
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
3 years ago
4 weeks ago
// 初始化元素的事件结构和主处理器,如果这是第一个
events = elemData.events;
if ( !events ) {
elemData.events = events = {};
}
eventHandle = elemData.handle;
if ( !eventHandle ) {
elemData.handle = eventHandle = function( e ) {
// 丢弃jQuery.event.trigger()的第二个事件
// 当一个页面卸载后调用事件
return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// 将elem作为handle函数的属性添加以防止IE非原生事件的内存泄漏
eventHandle.elem = elem;
}
}
3 years ago
};
// Handle multiple events separated by a space
// jQuery(...).bind("mouseover mouseout", fn);
4 weeks ago
// 将types字符串修剪并分割成数组
types = jQuery.trim( hoverHack(types) ).split( " " );
for ( t = 0; t < types.length; t++ ) {
// 通过正则表达式获取事件类型和命名空间
tns = rtypenamespace.exec( types[t] ) || [];
type = tns[1];
namespaces = ( tns[2] || "" ).split( "." ).sort();
// 如果事件类型发生变化,使用变化后的类型的特定事件处理器
special = jQuery.event.special[ type ] || {};
// 如果定义了选择器确定特殊事件API类型否则使用给定的类型
type = ( selector ? special.delegateType : special.bindType ) || type;
// 根据新重置的类型更新special
special = jQuery.event.special[ type ] || {};
// handleObj将被传递给所有事件处理器
handleObj = jQuery.extend({
type: type,
origType: tns[1],
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
quick: selector && quickParse( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// 如果我们是第一个,初始化事件处理器队列
handlers = events[ type ];
if ( !handlers ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// 只有当特殊事件处理器返回false时才使用addEventListener/attachEvent
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// 将全局事件处理器绑定到元素上
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
3 years ago
4 weeks ago
if ( special.add ) {
special.add.call( elem, handleObj );
3 years ago
4 weeks ago
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
3 years ago
}
}
4 weeks ago
// 添加到元素的处理器列表中,代表在前面
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
3 years ago
}
4 weeks ago
// 跟踪哪些事件曾经被使用过,用于事件优化
jQuery.event.global[ type ] = true;
3 years ago
}
4 weeks ago
// 将elem置空以防止IE中的内存泄漏
elem = null;
},
3 years ago
4 weeks ago
// 从元素上移除一个或一组事件
remove: function( elem, types, handler, selector, mappedTypes ) {
3 years ago
4 weeks ago
var elemData = jQuery.hasData( elem ) && jQuery._data( elem ),
t, tns, type, origType, namespaces, origCount,
j, events, special, handle, eventType, handleObj;
3 years ago
4 weeks ago
if ( !elemData || !(events = elemData.events) ) {
return;
}
3 years ago
4 weeks ago
// 为types的每个类型.namespace;类型可能被省略
types = jQuery.trim( hoverHack( types || "" ) ).split(" ");
for ( t = 0; t < types.length; t++ ) {
tns = rtypenamespace.exec( types[t] ) || [];
type = origType = tns[1];
namespaces = tns[2];
3 years ago
4 weeks ago
// 如果没有类型,为元素解除所有事件(在此命名空间下,如果提供了)
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
3 years ago
4 weeks ago
special = jQuery.event.special[ type ] || {};
type = ( selector? special.delegateType : special.bindType ) || type;
eventType = events[ type ] || [];
origCount = eventType.length;
namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.)?") + "(\\.|$)") : null;
3 years ago
4 weeks ago
// 移除匹配的事件
for ( j = 0; j < eventType.length; j++ ) {
handleObj = eventType[ j ];
3 years ago
4 weeks ago
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !namespaces || namespaces.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
eventType.splice( j--, 1 );
3 years ago
4 weeks ago
if ( handleObj.selector ) {
eventType.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
3 years ago
}
4 weeks ago
}
// 如果eventType被移除且没有更多处理器存在则移除通用事件处理器
// (避免在移除特殊事件处理器时出现潜在的无限递归)
if ( eventType.length === 0 && origCount !== eventType.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
3 years ago
}
4 weeks ago
delete events[ type ];
3 years ago
}
}
4 weeks ago
// 如果它不再被使用则移除expando
if ( jQuery.isEmptyObject( events ) ) {
handle = elemData.handle;
if ( handle ) {
handle.elem = null;
3 years ago
}
4 weeks ago
// removeData也检查空并清除expando如果为空
// 因此使用它代替delete
jQuery.removeData( elem, [ "events", "handle" ], true );
3 years ago
}
4 weeks ago
},
3 years ago
4 weeks ago
// 如果没有附加处理器,则可以安全地短路的事件。
// 原生DOM事件不应被添加它们可能有内联处理器。
customEvent: {
"getData": true,
"setData": true,
"changeData": true
},
3 years ago
4 weeks ago
// 触发事件
trigger: function( event, data, elem, onlyHandlers ) {
// 不要在文本和注释节点上做事件
if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) {
return;
}
3 years ago
4 weeks ago
// 事件对象或事件类型
var type = event.type || event,
namespaces = [],
cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType;
3 years ago
4 weeks ago
// focus/blur变为focusin/out确保我们不是在现在触发它们
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
3 years ago
4 weeks ago
if ( type.indexOf( "!" ) >= 0 ) {
// 独家事件只触发确切的事件(无命名空间)
type = type.slice(0, -1);
exclusive = true;
}
3 years ago
4 weeks ago
if ( type.indexOf( "." ) >= 0 ) {
// 命名空间触发创建一个正则表达式来匹配handle()中的事件类型
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
3 years ago
4 weeks ago
if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) {
// 没有jQuery处理器用于此事件类型它不能有内联处理器
return;
}
3 years ago
4 weeks ago
// 调用者可以传入一个Event对象、对象或只是一个事件类型字符串
event = typeof event === "object" ?
// jQuery.Event对象
event[ jQuery.expando ] ? event :
// 对象字面量
new jQuery.Event( type, event ) :
// 只是事件类型(字符串)
new jQuery.Event( type );
event.type = type;
event.isTrigger = true;
event.exclusive = exclusive;
event.namespace = namespaces.join( "." );
event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)") : null;
ontype = type.indexOf( ":" ) < 0 ? "on" + type : "";
// 处理全局触发
if ( !elem ) {
// TODO: 停止嘲笑数据缓存;移除全局事件并总是附加到文档
cache = jQuery.cache;
for ( i in cache ) {
if ( cache[ i ].events && cache[ i ].events[ type ] ) {
jQuery.event.trigger( event, data, cache[ i ].handle.elem, true );
}
3 years ago
}
4 weeks ago
return;
3 years ago
}
4 weeks ago
// 清理事件以防它被重用
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
3 years ago
4 weeks ago
// 克隆任何传入的数据并在前面添加事件,创建处理器参数列表
data = data != null ? jQuery.makeArray( data ) : [];
data.unshift( event );
3 years ago
4 weeks ago
// 允许特殊事件超越常规
special = jQuery.event.special[ type ] || {};
if ( special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
3 years ago
}
4 weeks ago
// 根据W3C事件规范预先确定事件传播路径
// 冒泡到文档然后到窗口注意全局ownerDocument变量#9724
eventPath = [[ elem, special.bindType || type ]];
3 years ago
4 weeks ago
if ( !only Handlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode;
old = null;
for ( ; cur; cur = cur.parentNode ) {
eventPath.push([ cur, bubbleType ]);
old = cur;
}
3 years ago
4 weeks ago
// 只有在到达文档时才添加窗口例如不是普通对象或脱离DOM
if ( old && old === elem.ownerDocument ) {
eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]);
}
3 years ago
}
4 weeks ago
// 在事件路径上触发处理器
for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) {
3 years ago
4 weeks ago
cur = eventPath[i][0];
event.type = eventPath[i][1];
3 years ago
4 weeks ago
handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// 注意这是一个裸JS函数而不是jQuery处理器
handle = ontype && cur[ ontype ];
if ( handle && jQuery.acceptData( cur ) && handle.apply( cur, data ) === false ) {
event.preventDefault();
}
3 years ago
}
4 weeks ago
event.type = type;
3 years ago
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) &&
!(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction() check here because IE6/7 fails that test.
// Don't do default actions on window, that's where global variables be (#6170)
// IE<9 dies on focus/blur to hidden element (#1486)
if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
old = elem[ ontype ];
if ( old ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
elem[ type ]();
jQuery.event.triggered = undefined;
if ( old ) {
elem[ ontype ] = old;
}
}
}
}
return event.result;
},
4 weeks ago
// dispatch 函数负责触发事件,并执行相应的事件处理程序
dispatch: function( event ) {
3 years ago
4 weeks ago
// 将原生事件对象转换为可写的 jQuery.Event 对象
event = jQuery.event.fix( event || window.event );
3 years ago
4 weeks ago
// 获取与事件类型相关联的处理程序数组
var handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []),
delegateCount = handlers.delegateCount,
args = [].slice.call( arguments, 0 ),
run_all = !event.exclusive && !event.namespace,
special = jQuery.event.special[ event.type ] || {},
handlerQueue = [],
i, j, cur, jqcur, ret, selMatch, matched, matches, handleObj, sel, related;
3 years ago
4 weeks ago
// 用修正后的 jQuery.Event 替换原生事件对象
args[0] = event;
event.delegateTarget = this;
3 years ago
4 weeks ago
// 调用映射类型的 preDispatch 钩子,如果需要可以终止事件
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
3 years ago
4 weeks ago
// 确定如果有委托事件应该运行的处理程序
if ( delegateCount && !(event.button && event.type === "click") ) {
3 years ago
4 weeks ago
// 为 .is() 重用预生成的单个 jQuery 对象
jqcur = jQuery(this);
jqcur.context = this.ownerDocument || this;
3 years ago
4 weeks ago
for ( cur = event.target; cur != this; cur = cur.parentNode || this ) {
3 years ago
4 weeks ago
// 不处理禁用元素上的事件(#6911, #8165
if ( cur.disabled !== true ) {
selMatch = {};
matches = [];
jqcur[0] = cur;
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
sel = handleObj.selector;
3 years ago
4 weeks ago
if ( selMatch[ sel ] === undefined ) {
selMatch[ sel ] = (
handleObj.quick ? quickIs( cur, handleObj.quick ) : jqcur.is( sel )
);
}
if ( selMatch[ sel ] ) {
matches.push( handleObj );
}
3 years ago
}
4 weeks ago
if ( matches.length ) {
handlerQueue.push({ elem: cur, matches: matches });
3 years ago
}
}
}
}
4 weeks ago
// 添加剩余的(直接绑定的)处理程序
if ( handlers.length > delegateCount ) {
handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) });
}
3 years ago
4 weeks ago
// 首先运行委托;它们可能希望停止我们的传播
for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) {
matched = handlerQueue[ i ];
event.currentTarget = matched.elem;
3 years ago
4 weeks ago
for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) {
handleObj = matched.matches[ j ];
3 years ago
4 weeks ago
if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) {
3 years ago
4 weeks ago
event.data = handleObj.data;
event.handleObj = handleObj;
3 years ago
4 weeks ago
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
3 years ago
.apply( matched.elem, args );
4 weeks ago
if ( ret !== undefined ) {
event.result = ret;
if ( ret === false ) {
event.preventDefault();
event.stopPropagation();
}
3 years ago
}
}
}
}
4 weeks ago
// 调用映射类型的 postDispatch 钩子
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
3 years ago
4 weeks ago
return event.result;
},
3 years ago
4 weeks ago
// 包括一些 KeyEvent 和 MouseEvent 共享的事件属性
props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
3 years ago
4 weeks ago
fixHooks: {},
3 years ago
4 weeks ago
// 处理键盘事件的钩子
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
3 years ago
}
4 weeks ago
},
3 years ago
4 weeks ago
// 处理鼠标事件的钩子
mouseHooks: {
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var eventDoc, doc, body,
button = original.button,
fromElement = original.fromElement;
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
3 years ago
4 weeks ago
if ( !event.relatedTarget && fromElement ) {
event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
}
3 years ago
4 weeks ago
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
3 years ago
}
4 weeks ago
},
3 years ago
4 weeks ago
// 修正事件对象的函数
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
3 years ago
}
4 weeks ago
var i, prop,
originalEvent = event,
fixHook = jQuery.event.fixHooks[ event.type ] || {},
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
3 years ago
4 weeks ago
event = jQuery.Event( originalEvent );
3 years ago
4 weeks ago
for ( i = copy.length; i; ) {
prop = copy[ --i ];
event[ prop ] = originalEvent[ prop ];
}
3 years ago
4 weeks ago
if ( !event.target ) {
event.target = originalEvent.srcElement || document;
}
3 years ago
4 weeks ago
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
3 years ago
4 weeks ago
if ( event.metaKey === undefined ) {
event.metaKey = event.ctrlKey;
}
3 years ago
4 weeks ago
return fixHook.filter? fixHook.filter( event, originalEvent ) : event;
3 years ago
},
4 weeks ago
// 特殊事件的处理
special: {
ready: {
setup: jQuery.bindReady
},
load: {
noBubble: true
},
focus: {
delegateType: "focusin"
},
blur: {
delegateType: "focusout"
3 years ago
},
4 weeks ago
beforeunload: {
setup: function( data, namespaces, eventHandle ) {
if ( jQuery.isWindow( this ) ) {
this.onbeforeunload = eventHandle;
}
},
teardown: function( namespaces, eventHandle ) {
if ( this.onbeforeunload === eventHandle ) {
this.onbeforeunload = null;
}
}
}
3 years ago
},
4 weeks ago
// 模拟事件的函数
simulate: function( type, elem, event, bubble ) {
var e = jQuery.extend(
new jQuery.Event(),
event,
{ type: type,
isSimulated: true,
originalEvent: {}
3 years ago
}
4 weeks ago
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
3 years ago
}
4 weeks ago
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
3 years ago
},
4 weeks ago
// 处理事件的脱绑和绑定
jQuery.event.handle = jQuery.event.dispatch;
3 years ago
4 weeks ago
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
3 years ago
}
4 weeks ago
} :
function( elem, type, handle ) {
if ( elem.detachEvent ) {
elem.detachEvent( "on" + type, handle );
}
};
3 years ago
4 weeks ago
// jQuery.Event 构造函数
jQuery.Event = function( src, props ) {
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
3 years ago
}
4 weeks ago
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false ||
src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;
} else {
this.type = src;
}
3 years ago
4 weeks ago
if ( props ) {
jQuery.extend( this, props );
}
3 years ago
4 weeks ago
this.timeStamp = src && src.timeStamp || jQuery.now();
this[ jQuery.expando ] = true;
};
3 years ago
4 weeks ago
function returnFalse() {
return false;
3 years ago
}
4 weeks ago
function returnTrue() {
return true;
3 years ago
}
4 weeks ago
// jQuery.Event 原型,提供 preventDefault, stopPropagation 等方法
jQuery.Event.prototype = {
preventDefault: function() {
this.isDefaultPrevented = returnTrue;
3 years ago
4 weeks ago
var e = this.originalEvent;
if ( !e ) {
return;
}
3 years ago
4 weeks ago
// if preventDefault exists run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
3 years ago
4 weeks ago
// otherwise set the returnValue property of the original event to false (IE)
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
this.isPropagationStopped = returnTrue;
3 years ago
4 weeks ago
var e = this.originalEvent;
if ( !e ) {
return;
3 years ago
}
4 weeks ago
// if stopPropagation exists run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// otherwise set the cancelBubble property of the original event to true (IE)
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
},
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse
3 years ago
};
4 weeks ago
// 创建 mouseenter/leave 事件
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var target = this,
related = event.relatedTarget,
handleObj = event.handleObj,
selector = handleObj.selector,
ret;
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
3 years ago
// IE submit delegation
if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
// Node name check avoids a VML-related crash in IE (#9807)
var elem = e.target,
form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
if ( form && !form._submit_attached ) {
jQuery.event.add( form, "submit._submit", function( event ) {
event._submit_bubble = true;
});
form._submit_attached = true;
}
});
// return undefined since we don't need an event listener
},
postDispatch: function( event ) {
// If form was submitted by the user, bubble the event up the tree
if ( event._submit_bubble ) {
delete event._submit_bubble;
if ( this.parentNode && !event.isTrigger ) {
jQuery.event.simulate( "submit", this.parentNode, event, true );
}
}
},
teardown: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
jQuery.event.remove( this, "._submit" );
}
};
}
// IE change delegation and checkbox/radio fix
4 weeks ago
// 判断jQuery是否不支持change事件冒泡如果!jQuery.support.changeBubbles为真表示不支持
if (!jQuery.support.changeBubbles ) {
3 years ago
4 weeks ago
// 为jQuery的事件系统中的'special'对象添加名为'change'的自定义事件相关配置
jQuery.event.special.change = {
3 years ago
4 weeks ago
// 'setup'函数会在绑定事件时被调用,用于进行一些初始化设置
setup: function() {
// 测试当前节点的节点名是否匹配特定的表单元素相关的正则表达式rformElems应该是在别处定义的用于匹配表单元素节点名的正则
if ( rformElems.test( this.nodeName ) ) {
// 在IE浏览器中复选框checkbox和单选框radio在失去焦点blur时才触发'change'事件这里在点击click后且发生属性改变propertychange时触发它。
// 并且在'special.change.handle'中处理掉因失去焦点导致的重复的'change'事件触发情况。
// 但这样对于复选框和单选框在失去焦点后还是会第二次触发'onchange'事件。
if ( this.type === "checkbox" || this.type === "radio" ) {
// 为当前元素添加名为'propertychange._change'的事件监听器,当属性改变事件发生时执行下面的回调函数
jQuery.event.add( this, "propertychange._change", function( event ) {
// 如果属性改变事件的原始事件中属性名为'checked'(也就是复选框或单选框的选中状态改变了)
if ( event.originalEvent.propertyName === "checked" ) {
// 标记当前元素刚刚发生了改变
this._just_changed = true;
}
});
// 为当前元素添加名为'click._change'的事件监听器,当点击事件发生时执行下面的回调函数
jQuery.event.add( this, "click._change", function( event ) {
// 如果当前元素刚刚发生了改变且不是通过代码手动触发的事件(!event.isTrigger
if ( this._just_changed &&!event.isTrigger ) {
// 重置刚刚改变的标记
this._just_changed = false;
// 模拟触发'change'事件传递当前元素、原始点击事件以及一些其他相关参数最后一个参数true可能有特定含义比如冒泡相关等
jQuery.event.simulate( "change", this, event, true );
}
});
}
// 表示不需要执行默认的事件绑定逻辑了可能有特定的jQuery内部机制相关含义
return false;
3 years ago
}
4 weeks ago
// 如果是委托事件(意味着事件是绑定在父元素上,等待子元素触发的情况)
// 延迟添加一个针对后代输入元素的'change'事件处理程序
jQuery.event.add( this, "beforeactivate._change", function( e ) {
// 获取实际触发事件的目标元素
var elem = e.target;
// 再次测试目标元素的节点名是否匹配特定表单元素正则,并且该元素还没有添加过'_change'相关的事件处理程序(!elem._change_attached
if ( rformElems.test( elem.nodeName ) &&!elem._change_attached ) {
// 为目标元素添加名为'change._change'的事件监听器,当'change'事件发生时执行下面的回调函数
jQuery.event.add( elem, "change._change", function( event ) {
// 如果目标元素有父元素,并且事件不是模拟触发的(!event.isSimulated也不是通过代码手动触发的!event.isTrigger
if ( this.parentNode &&!event.isSimulated &&!event.isTrigger ) {
// 模拟触发父元素的'change'事件传递父元素、当前事件以及相关参数同样最后一个参数true可能和冒泡等有关
jQuery.event.simulate( "change", this.parentNode, event, true );
}
});
// 标记该元素已经添加过'_change'相关的事件处理程序了
elem._change_attached = true;
}
});
},
// 'handle'函数用于处理实际触发的事件,决定是否执行默认的事件处理逻辑等
handle: function( event ) {
// 获取实际触发事件的目标元素
var elem = event.target;
// 如果当前处理事件的对象不是目标元素本身可能是冒泡上来的情况等或者事件是模拟触发的event.isSimulated或者是通过代码手动触发的event.isTrigger或者目标元素不是单选框和复选框类型
if ( this!== elem || event.isSimulated || event.isTrigger || (elem.type!== "radio" && elem.type!== "checkbox") ) {
// 执行默认的事件处理程序也就是调用原本绑定的事件处理函数传递相关参数arguments包含了事件相关的参数等
return event.handleObj.handler.apply( this, arguments );
3 years ago
}
4 weeks ago
},
3 years ago
4 weeks ago
// 'teardown'函数会在解绑事件时被调用,用于清理相关的事件绑定等操作
teardown: function() {
// 移除当前元素上所有名称包含'._change'的事件监听器
jQuery.event.remove( this, "._change" );
3 years ago
4 weeks ago
// 返回当前节点的节点名是否匹配特定表单元素的正则表达式的测试结果(可能用于判断是否还有相关清理工作要做等)
return rformElems.test( this.nodeName );
3 years ago
}
4 weeks ago
};
}
3 years ago
4 weeks ago
// 判断jQuery是否不支持焦点进入focusin和焦点离开focusout事件冒泡如果!jQuery.support.focusinBubbles为真表示不支持
if (!jQuery.support.focusinBubbles ) {
// 遍历包含'focus'和'blur'的对象,将'focus'映射为'focusin''blur'映射为'focusout',进行相关操作
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
3 years ago
4 weeks ago
// 用于记录当前有多少个地方想要使用'focusin'或'focusout'事件初始化为0
var attaches = 0,
// 定义事件处理函数,用于模拟触发对应的'fix'(也就是'focusin'或'focusout')事件
handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
3 years ago
4 weeks ago
// 为jQuery的事件系统中的'special'对象添加名为'fix'(也就是'focusin'或'focusout')的自定义事件相关配置
jQuery.event.special[ fix ] = {
//'setup'函数会在绑定'focusin'或'focusout'事件时被调用,用于进行初始化设置
setup: function() {
// 当第一次有地方绑定该事件时attaches初始为0自增后为1
if ( attaches++ === 0 ) {
// 在文档对象上添加原生的'orig'(也就是'focus'或'blur')事件的捕获阶段监听器,绑定上面定义的'handler'函数
document.addEventListener( orig, handler, true );
}
},
// 'teardown'函数会在解绑'focusin'或'focusout'事件时被调用,用于清理相关操作
teardown: function() {
// 当所有绑定该事件的地方都解绑了attaches自减后为0
if ( --attaches === 0 ) {
// 移除文档对象上对应的原生'orig'(也就是'focus'或'blur')事件的捕获阶段监听器
document.removeEventListener( orig, handler, true );
}
}
3 years ago
};
4 weeks ago
});
}
3 years ago
4 weeks ago
// 使用jQuery.fn.extend方法来扩展jQuery的原型对象添加一系列与事件处理相关的方法
jQuery.fn.extend({
3 years ago
4 weeks ago
// on方法用于绑定事件可以有多种参数形式来处理不同的绑定场景
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var origFn, type;
3 years ago
4 weeks ago
// 第一种情况如果types参数是一个对象意味着可以传入多个事件类型及其对应的处理函数的映射形式
if ( typeof types === "object" ) {
// 如果selector参数不是字符串类型且不为null这里原注释中虽然注释掉了!= null判断但可能实际逻辑中有此考虑说明可能传入的参数形式是( types-Object, data )这种没有selector参数
if ( typeof selector!== "string" ) { // && selector!= null
// 将data参数赋值为原本的selector这里selector可能传了实际的数据对象等并将selector设为undefined符合( types-Object, data )的参数预期
data = data || selector;
selector = undefined;
3 years ago
}
4 weeks ago
// 遍历传入的types对象的每个属性也就是每个事件类型
for ( type in types ) {
// 递归调用on方法逐个绑定每个事件类型及其对应的处理函数实现对多个事件的绑定
this.on( type, selector, data, types[ type ], one );
3 years ago
}
4 weeks ago
// 返回当前的jQuery对象实例以便支持链式调用
return this;
3 years ago
}
4 weeks ago
// 第二种情况如果data和fn都为null说明传入的参数形式可能是( types, fn )这种将fn赋值为原本的selector然后将data和selector都设为undefined来符合预期的参数格式
if ( data == null && fn == null ) {
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
// 如果fn为null进一步判断selector的类型如果是字符串类型说明参数形式可能是( types, selector, fn )将fn赋值为原本的datadata设为undefined
if ( typeof selector === "string" ) {
fn = data;
data = undefined;
} else {
// 如果selector不是字符串类型参数形式可能是( types, data, fn )将fn赋值为原本的data将data赋值为原本的selector再将selector设为undefined
fn = data;
data = selector;
selector = undefined;
}
}
// 如果fn的值为false将fn指向一个名为returnFalse的函数这里returnFalse应该是在别处定义的可能返回false的函数用于特定的事件处理逻辑
if ( fn === false ) {
fn = returnFalse;
} else if (!fn ) {
// 如果fn为假值比如undefined、null等直接返回当前的jQuery对象实例不进行事件绑定操作
return this;
}
3 years ago
4 weeks ago
// 如果one参数的值为1表示只希望事件触发一次
if ( one === 1 ) {
origFn = fn;
// 重新定义fn函数在事件触发时先移除对应的事件绑定通过off方法这里的jQuery()创建了一个空的jQuery对象集合但不影响off方法的调用逻辑因为off方法内部可以处理这种情况根据event中的信息来确定要移除的事件然后再执行原本的事件处理函数origFn
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// 让新的fn函数继承原本origFn函数的唯一标识符guid如果origFn没有guid则生成一个新的guid保证调用者可以通过origFn来移除这个只触发一次的事件绑定
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
// 遍历当前jQuery对象集合中的每个元素调用jQuery.event.add方法为每个元素添加指定的事件绑定传入事件类型、处理函数、数据以及选择器等参数
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
3 years ago
4 weeks ago
// one方法是对on方法的一个简单封装用于方便地绑定只触发一次的事件直接调用on方法并传入参数1表示只触发一次
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
// off方法用于解绑事件同样有多种参数形式来应对不同的解绑场景
off: function( types, selector, fn ) {
// 如果types参数是一个已经触发过的jQuery.Event对象它有preventDefault、handleObj等属性说明是基于已触发事件对象来解绑对应的事件绑定
if ( types && types.preventDefault && types.handleObj ) {
// 获取事件对象中的handleObj属性它包含了事件相关的原始类型、命名空间、选择器以及处理函数等关键信息
var handleObj = types.handleObj;
// 通过事件对象中的delegateTarget属性找到对应的元素可能是委托事件绑定的目标元素然后调用off方法来解绑该元素上符合条件的事件条件包括原始事件类型、命名空间、选择器以及处理函数等信息
jQuery( types.delegateTarget ).off(
handleObj.namespace? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
3 years ago
}
4 weeks ago
// 如果types参数是一个对象意味着可以传入多个事件类型及其对应的处理函数的映射形式来批量解绑事件
if ( typeof types === "object" ) {
// 遍历传入的types对象的每个属性也就是每个事件类型
for ( var type in types ) {
// 递归调用off方法逐个解绑每个事件类型及其对应的处理函数实现对多个事件的解绑
this.off( type, selector, types[ type ] );
}
return this;
3 years ago
}
4 weeks ago
// 如果selector参数是false或者是一个函数类型说明可能传入的参数形式是( types [, fn] )将fn赋值为原本的selector然后将selector设为undefined来符合预期的参数格式
if ( selector === false || typeof selector === "function" ) {
fn = selector;
3 years ago
selector = undefined;
}
4 weeks ago
// 如果fn的值为false将fn指向一个名为returnFalse的函数和on方法中类似的处理逻辑
if ( fn === false ) {
fn = returnFalse;
3 years ago
}
4 weeks ago
// 遍历当前jQuery对象集合中的每个元素调用jQuery.event.remove方法为每个元素移除指定的事件绑定传入事件类型、处理函数以及选择器等参数
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
3 years ago
4 weeks ago
// bind方法是对on方法的一种简化调用形式用于绑定事件它传入事件类型、数据以及处理函数将选择器参数设为null也就是不涉及选择器相关的复杂事件绑定场景
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
// unbind方法是对off方法的一种简化调用形式用于解绑事件它传入事件类型以及处理函数将选择器参数设为null也就是不涉及选择器相关的复杂事件解绑场景
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
// live方法用于给当前元素的上下文context绑定事件通过调用on方法传入事件类型、选择器this.selector表示当前元素相关的选择器、数据以及处理函数等来实现实现一种类似事件委托的效果让符合选择器的后代元素可以响应事件
live: function( types, data, fn ) {
jQuery( this.context ).on( types, this.selector, data, fn );
3 years ago
return this;
4 weeks ago
},
3 years ago
4 weeks ago
// die方法用于移除通过live方法绑定的事件通过调用off方法传入事件类型以及选择器如果this.selector不存在则使用"**"作为通配符选择器,确保能移除相关的事件绑定)等来实现
die: function( types, fn ) {
jQuery( this.context ).off( types, this.selector || "**", fn );
3 years ago
return this;
4 weeks ago
},
3 years ago
4 weeks ago
// delegate方法是对on方法的另一种调用形式用于进行事件委托绑定传入选择器、事件类型、数据以及处理函数等参数本质上就是调用on方法来完成事件委托相关的事件绑定操作
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
3 years ago
4 weeks ago
// undelegate方法用于移除通过delegate方法绑定的事件根据传入参数的个数来判断具体的解绑逻辑如果只传入一个参数说明可能是基于命名空间等来解绑调用off方法并传入相应参数如果传入多个参数就是常规的传入事件类型、选择器以及处理函数等参数来解绑对应的事件委托绑定
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length == 1? this.off( selector, "**" ) : this.off( types, selector, fn );
},
3 years ago
4 weeks ago
// trigger方法用于触发指定的事件遍历当前jQuery对象集合中的每个元素调用jQuery.event.trigger方法来触发传入的事件类型以及传递相关的数据触发每个元素上对应的事件
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
3 years ago
4 weeks ago
// triggerHandler方法用于触发指定的事件但和trigger方法不同的是它只在第一个元素this[0]上触发事件并且以一种特殊的方式触发最后一个参数true可能有特定的内部触发机制含义比如不进行事件冒泡等如果存在第一个元素则调用jQuery.event.trigger方法触发事件并返回结果否则返回undefined之类的值因为没有元素可触发事件
triggerHandler: function( type, data ) {
if ( this[0] ) {
return jQuery.event.trigger( type, data, this[0], true );
}
},
3 years ago
4 weeks ago
// toggle方法用于实现点击事件的切换效果也就是每次点击执行不同的函数
toggle: function( fn ) {
// 保存传入的所有参数,方便在闭包中访问
var args = arguments,
guid = fn.guid || jQuery.guid++,
i = 0,
toggler = function( event ) {
// 计算出当前应该执行的函数索引通过获取当前元素上存储的上一次执行的函数索引通过jQuery._data方法获取以"lastToggle" + fn.guid为键初始化为0如果不存在则默认为0然后取余得到本次要执行的函数索引
var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i;
// 更新当前元素上存储的上一次执行的函数索引自增1为下一次点击做准备
jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 );
// 阻止事件的默认行为比如阻止链接的跳转等如果是在点击链接等可触发默认行为的元素上绑定的toggle事件
event.preventDefault();
3 years ago
4 weeks ago
// 执行对应的函数并返回执行结果如果结果为假值则返回false可能用于一些逻辑判断等
return args[ lastToggle ].apply( this, arguments ) || false;
};
3 years ago
4 weeks ago
// 让toggler函数继承传入函数的唯一标识符guid保证可以通过这个标识符来统一管理相关的事件绑定等操作
toggler.guid = guid;
// 遍历所有传入的函数参数让每个函数都继承相同的唯一标识符guid使得它们可以作为一组来进行相关的事件绑定和管理
while ( i < args.length ) {
args[ i++ ].guid = guid;
}
3 years ago
4 weeks ago
// 将toggler函数绑定到当前jQuery对象集合的点击事件click实现点击切换执行不同函数的效果
return this.click( toggler );
},
3 years ago
4 weeks ago
// hover方法用于方便地绑定鼠标移入mouseenter和鼠标移出mouseleave事件传入对应的处理函数如果只传入一个函数则同时作为鼠标移入和移出的处理函数通过链式调用分别调用mouseenter和mouseleave方法来绑定事件
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
3 years ago
}
4 weeks ago
});
3 years ago
4 weeks ago
// 遍历一个包含众多常见事件名称的字符串,通过空格分割后得到的事件名称数组,对每个事件名称进行相关操作
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
3 years ago
4 weeks ago
// 为jQuery.fn对象也就是jQuery的原型对象添加以事件名称为属性名的方法用于方便地绑定对应事件
jQuery.fn[ name ] = function( data, fn ) {
if ( fn == null ) {
fn = data;
data = null;
}
3 years ago
4 weeks ago
// 根据传入参数的个数来决定是绑定事件传入了data和fn参数还是触发事件只传入事件名称作为参数没有其他参数如果传入参数个数大于0则调用on方法绑定事件否则调用trigger方法触发事件
return arguments.length > 0?
this.on( name, null, data, fn ) :
this.trigger( name );
};
3 years ago
4 weeks ago
// 如果jQuery.attrFn对象存在可能是用于处理元素属性相关的一个对象和事件有一定关联等情况在其上面标记当前事件名称对应的属性为true具体用途可能要看jQuery.attrFn在其他地方的使用逻辑
if ( jQuery.attrFn ) {
jQuery.attrFn[ name ] = true;
3 years ago
}
4 weeks ago
// 如果事件名称匹配键盘事件相关的正则表达式rkeyEvent应该是在别处定义的用于判断键盘事件的正则将当前事件名称对应的事件修复钩子fixHooks用于在事件处理过程中进行一些兼容性等方面的修复操作指向jQuery.event.keyHooks应该是处理键盘事件的通用钩子函数等
if ( rkeyEvent.test( name ) ) {
jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks;
}
3 years ago
4 weeks ago
// 如果事件名称匹配鼠标事件相关的正则表达式rmouseEvent应该是在别处定义的用于判断鼠标事件的正则将当前事件名称对应的事件修复钩子fixHooks指向jQuery.event.mouseHooks应该是处理鼠标事件的通用钩子函数等
if ( rmouseEvent.test( name ) ) {
jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks;
}
});
3 years ago
/*!
* Sizzle CSS Selector Engine
* Copyright 2011, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
* More information: http://sizzlejs.com/
*/
4 weeks ago
// 立即执行函数,创建一个独立的作用域,避免变量污染全局环境
(function () {
// 定义一个正则表达式用于分割选择器字符串,它能匹配各种复杂的选择器语法结构,例如括号包裹的内容、方括号包裹的内容、转义字符、普通字符等,并提取相关部分
var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
// 生成一个随机的扩展属性名称(用于在对象上添加自定义属性来做一些标记等操作,避免与其他属性冲突),通过在随机数基础上处理得到一个字符串
expando = "sizcache" + (Math.random() + '').replace('.', ''),
done = 0,
// 获取Object原型上的toString方法的引用用于后续判断对象类型
toString = Object.prototype.toString,
hasDuplicate = false,
baseHasDuplicate = true,
// 用于匹配转义字符的正则表达式
rBackslash = /\\/g,
// 用于匹配回车换行符的正则表达式
rReturn = /\r\n/g,
// 用于匹配非单词字符(比如标点符号等)的正则表达式
rNonWord = /\W/;
// 这里检查JavaScript引擎是否使用了某种优化导致不总是调用我们的比较函数。如果是这种情况目前已知包括Google Chrome则丢弃hasDuplicate的值。
// 通过对包含两个0的数组进行排序操作并在排序比较函数中修改baseHasDuplicate的值来检测这种情况
[0, 0].sort(function () {
baseHasDuplicate = false;
return 0;
});
3 years ago
4 weeks ago
// 定义Sizzle函数它是主要的选择器解析和元素查找函数用于根据给定的选择器在指定的上下文中查找匹配的元素
var Sizzle = function (selector, context, results, seed) {
// 如果没有传入results参数则初始化为空数组用于存储查找结果
results = results || [];
// 如果没有传入context参数则默认为文档对象document表示查找的上下文范围
context = context || document;
3 years ago
4 weeks ago
// 保存原始的查找上下文对象,方便后续可能的使用
var origContext = context;
3 years ago
4 weeks ago
// 如果传入的上下文对象不是元素节点nodeType为1表示元素节点9表示文档节点则直接返回空数组因为无法在这样的对象中查找元素
if (context.nodeType!== 1 && context.nodeType!== 9) {
return [];
}
3 years ago
4 weeks ago
// 如果没有传入选择器或者选择器类型不是字符串也直接返回results此时可能为空数组不符合查找元素的基本要求
if (!selector || typeof selector!== "string") {
return results;
3 years ago
}
4 weeks ago
// 定义一系列局部变量,用于后续在选择器解析和元素查找过程中的各种操作
var m, set, checkSet, extra, ret, cur, pop, i,
prune = true,
// 判断上下文是否是XML文档环境通过调用Sizzle.isXML方法来判断该方法应该在别处定义
contextXML = Sizzle.isXML(context),
// 用于存储分割后的选择器各个部分,方便后续按顺序处理
parts = [],
soFar = selector;
// 重置chunker正则表达式的匹配位置从开头开始匹配然后通过循环不断用chunker正则表达式分割选择器字符串
do {
chunker.exec("");
m = chunker.exec(soFar);
if (m) {
// 更新剩余未处理的选择器部分
soFar = m[3];
// 将匹配到的选择器部分添加到parts数组中
parts.push(m[1]);
// 如果存在分隔符(表示后面还有更多选择器部分需要处理),提取额外的部分并跳出循环,后续会单独处理这部分
if (m[2]) {
extra = m[3];
break;
}
}
} while (m);
3 years ago
4 weeks ago
// 如果分割后的选择器部分数量大于1并且原始选择器匹配特定的位置相关模式origPOS应该是在别处定义的用于判断位置相关选择器的正则或函数等
if (parts.length > 1 && origPOS.exec(selector)) {
3 years ago
4 weeks ago
// 如果分割后的部分只有两个且第一个部分是相对位置选择器Expr.relative应该是一个包含各种相对位置选择器相关信息的对象在别处定义
if (parts.length === 2 && Expr.relative[parts[0]]) {
// 调用posProcess函数应该是处理位置相关选择器的函数在别处定义来处理这两个部分组成的选择器并获取匹配的元素集合
set = posProcess(parts[0] + parts[1], context, seed);
3 years ago
4 weeks ago
} else {
// 如果第一个部分是相对位置选择器将初始的元素集合设为包含上下文对象的数组也就是从上下文开始查找否则调用Sizzle函数递归调用自身查找第一个选择器部分对应的元素集合
set = Expr.relative[parts[0]]?
[context] :
Sizzle(parts.shift(), context);
// 循环处理剩余的选择器部分
while (parts.length) {
selector = parts.shift();
// 如果当前选择器部分是相对位置选择器,将其与下一个部分合并(因为相对位置选择器通常要和后面的部分一起处理才有意义)
if (Expr.relative[selector]) {
selector += parts.shift();
}
// 再次调用posProcess函数处理合并后的选择器并更新匹配的元素集合
set = posProcess(selector, set, seed);
}
}
3 years ago
4 weeks ago
} else {
// 如果选择器的根部分第一个部分是ID选择器并且满足一些其他条件比如不是内层选择器也是ID选择器等情况这样做可能是为了优化查找速度则采取快捷方式先查找该ID对应的元素并更新上下文为找到的元素如果有的话
if (!seed && parts.length > 1 && context.nodeType === 9 &&!contextXML &&
Expr.match.ID.test(parts[0]) &&!Expr.match.ID.test(parts[parts.length - 1])) {
ret = Sizzle.find(parts.shift(), context, contextXML);
context = ret.expr?
Sizzle.filter(ret.expr, ret.set)[0] :
ret.set[0];
3 years ago
}
4 weeks ago
// 如果存在上下文(也就是前面处理后找到了合适的查找起点)
if (context) {
// 如果传入了seed参数构建一个包含expr和set属性的对象expr为剩余选择器部分的最后一个通过pop取出set为传入的seed可能是已经筛选过的元素集合等否则调用Sizzle.find函数查找最后一个选择器部分对应的元素集合根据不同情况传入合适的上下文等参数
ret = seed?
{ expr: parts.pop(), set: makeArray(seed) } :
Sizzle.find(parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode? context.parentNode : context, contextXML);
3 years ago
4 weeks ago
// 如果找到的结果中有expr属性表示可能经过了筛选等操作则调用Sizzle.filter函数进一步过滤元素集合否则直接使用找到的元素集合
set = ret.expr?
Sizzle.filter(ret.expr, ret.set) :
ret.set;
3 years ago
4 weeks ago
// 如果还有剩余的选择器部分需要处理,则将当前的元素集合转为数组(方便后续循环处理)
if (parts.length > 0) {
checkSet = makeArray(set);
3 years ago
4 weeks ago
} else {
// 如果没有剩余选择器部分了设置prune为false表示不需要进行后续的一些筛选操作具体要看后面的逻辑可能和元素集合的处理方式有关
prune = false;
}
3 years ago
4 weeks ago
// 循环处理剩余的选择器部分(从后往前处理,因为可能涉及到相对位置选择器等依赖后面元素的情况)
while (parts.length) {
cur = parts.pop();
pop = cur;
3 years ago
4 weeks ago
// 如果当前选择器部分不是相对位置选择器,将其设为空字符串(可能有特殊处理逻辑,比如当作普通选择器等情况)
if (!Expr.relative[cur]) {
cur = "";
} else {
// 如果是相对位置选择器,取出下一个选择器部分(可能和当前相对位置选择器配合使用)
pop = parts.pop();
}
3 years ago
4 weeks ago
// 如果取出的配合使用的选择器部分为null可能没有下一个部分了等情况则将其设为上下文对象也就是当作相对当前上下文来处理
if (pop == null) {
pop = context;
}
3 years ago
4 weeks ago
// 调用相对位置选择器对应的处理函数Expr.relative[cur]应该是一个函数根据不同的相对位置选择器有不同的处理逻辑传入当前的元素集合、相关的参考元素以及是否是XML文档环境等参数来更新元素集合
Expr.relative[cur](checkSet, pop, contextXML);
}
3 years ago
} else {
4 weeks ago
// 如果没有合适的上下文比如传入的上下文不符合要求等情况将checkSet和parts都设为空数组后续可能会根据这个情况进行错误处理等操作
checkSet = parts = [];
3 years ago
}
}
4 weeks ago
// 如果checkSet为空可能前面处理过程中没有正确赋值等情况则将其设为set也就是前面查找得到的元素集合
if (!checkSet) {
checkSet = set;
}
3 years ago
4 weeks ago
// 如果checkSet仍然为空说明出现了错误调用Sizzle.error函数应该是用于输出错误信息等的函数在别处定义传入当前的选择器部分或者整个选择器字符串来提示错误
if (!checkSet) {
Sizzle.error(cur || selector);
}
3 years ago
4 weeks ago
// 判断checkSet的类型是否是数组通过调用toString方法并判断返回值是否是"[object Array]"来确定)
if (toString.call(checkSet) === "[object Array]") {
// 如果不需要进行筛选操作prune为false直接将checkSet中的元素添加到results数组中通过apply方法将元素逐个添加模拟数组的pushAll操作
if (!prune) {
results.push.apply(results, checkSet);
} else if (context && context.nodeType === 1) {
// 如果需要筛选并且上下文是元素节点循环遍历checkSet数组判断每个元素是否符合条件比如元素存在、是元素节点并且满足Sizzle.contains方法判断的包含关系等Sizzle.contains应该是判断元素包含关系的函数在别处定义符合条件的元素对应的set中的元素添加到results数组中
for (i = 0; checkSet[i]!= null; i++) {
if (checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i]))) {
results.push(set[i]);
}
}
3 years ago
4 weeks ago
} else {
// 如果需要筛选但上下文不是元素节点循环遍历checkSet数组只判断元素是否是元素节点是元素节点的对应的set中的元素添加到results数组中
for (i = 0; checkSet[i]!= null; i++) {
if (checkSet[i] && checkSet[i].nodeType === 1) {
results.push(set[i]);
}
}
3 years ago
}
4 weeks ago
} else {
// 如果checkSet不是数组类型调用makeArray函数应该是将类数组对象等转为真正数组的函数在别处定义将其转为数组并将结果添加到results数组中
makeArray(checkSet, results);
3 years ago
}
4 weeks ago
// 如果存在额外的选择器部分(前面分割出来的,还未处理的部分)
if (extra) {
// 递归调用Sizzle函数传入额外的选择器部分、原始的上下文对象以及results数组用于继续添加查找结果和seed可能用于延续之前的查找逻辑等
Sizzle(extra, origContext, results, seed);
// 调用Sizzle.uniqueSort函数应该是对结果数组进行去重和排序的函数在别处定义对results数组进行处理确保结果的唯一性和顺序性
Sizzle.uniqueSort(results);
}
3 years ago
4 weeks ago
// 返回最终的查找结果数组
return results;
};
3 years ago
4 weeks ago
// 定义Sizzle对象的uniqueSort方法用于对结果数组进行去重和排序操作
Sizzle.uniqueSort = function (results) {
// 如果sortOrder存在sortOrder应该是在别处定义的用于排序的规则相关变量可能是一个比较函数等用于确定元素的排序顺序
if (sortOrder) {
// 恢复hasDuplicate的值为baseHasDuplicate的值前面可能在某些检测情况下对baseHasDuplicate进行了修改这里重新赋值给hasDuplicate用于后续判断是否有重复元素
hasDuplicate = baseHasDuplicate;
// 使用sortOrder规则对results数组进行排序改变数组内元素的顺序使其符合指定的排序要求
results.sort(sortOrder);
// 如果存在重复元素hasDuplicate为真
if (hasDuplicate) {
// 从索引为1开始遍历results数组因为比较重复是从第二个元素开始和前一个元素对比
for (var i = 1; i < results.length; i++) {
// 如果当前元素和前一个元素相等(说明是重复元素)
if (results[i] === results[i - 1]) {
// 使用splice方法从数组中移除当前这个重复元素同时将索引i自减1因为移除元素后后面的元素会向前移动一位下次循环需要再次检查当前位置的元素是否和前一个重复
results.splice(i--, 1);
}
}
3 years ago
}
}
4 weeks ago
// 返回经过去重和排序后的results数组
return results;
};
3 years ago
4 weeks ago
// 定义Sizzle对象的matches方法它通过调用Sizzle函数传入表达式、空的上下文、空的初始结果以及给定的元素集合set来判断给定的元素集合中的元素是否匹配指定的表达式expr本质上是利用Sizzle函数进行元素匹配的一种封装
Sizzle.matches = function (expr, set) {
return Sizzle(expr, null, null, set);
};
3 years ago
4 weeks ago
// 定义Sizzle对象的matchesSelector方法它通过调用Sizzle函数传入表达式、空的上下文、空的初始结果以及包含单个节点node的数组然后判断返回的结果数组长度是否大于0以此来确定给定的节点是否匹配指定的表达式expr也就是判断单个节点是否符合特定的选择器要求的一种方式
Sizzle.matchesSelector = function (node, expr) {
return Sizzle(expr, null, null, [node]).length > 0;
};
3 years ago
4 weeks ago
// 定义Sizzle对象的find方法用于查找与给定表达式expr匹配的元素集合在指定的上下文context中进行查找同时考虑是否是XML文档环境isXML
Sizzle.find = function (expr, context, isXML) {
var set, i, len, match, type, left;
3 years ago
4 weeks ago
// 如果没有传入表达式expr直接返回空数组因为没有查找依据
if (!expr) {
return [];
}
3 years ago
4 weeks ago
// 遍历Expr.order数组Expr.order应该是在别处定义的包含了各种查找类型的顺序相关信息用于按顺序尝试不同的查找方式
for (i = 0, len = Expr.order.length; i < len; i++) {
type = Expr.order[i];
// 使用对应类型的左匹配正则Expr.leftMatch[type]不同的查找类型有不同的匹配正则表达式用于提取表达式中的关键部分来尝试匹配传入的表达式expr如果匹配成功
if ((match = Expr.leftMatch[type].exec(expr))) {
// 获取匹配到的左边部分(可能是选择器的关键标识部分等)
left = match[1];
// 移除匹配结果数组中的第二个元素(具体用途可能和不同查找类型的处理逻辑有关,这里不清楚具体原因,但从代码逻辑看是要去掉这个元素)
match.splice(1, 1);
// 如果左边部分的最后一个字符不是转义字符(\),说明是正常的匹配情况
if (left.substr(left.length - 1)!== "\\") {
// 去除匹配结果数组中第二个元素经过前面的splice操作后这里的第二个元素对应的含义应该和具体查找类型相关可能是要去除一些转义相关的干扰等中的转义字符通过替换为空字符串的方式
match[1] = (match[1] || "").replace(rBackslash, "");
// 调用对应查找类型的查找函数Expr.find[type]不同类型有不同的查找逻辑实现在别处定义传入处理后的匹配结果、上下文以及是否是XML文档环境等参数获取查找到的元素集合
set = Expr.find[type](match, context, isXML);
// 如果查找到了元素集合不为null
if (set!= null) {
// 将表达式中已经匹配并处理过的部分替换为空字符串,也就是去掉已经查找过的部分,继续处理剩余的表达式部分
expr = expr.replace(Expr.match[type], "");
// 找到元素集合后就跳出循环,因为已经完成了本次查找任务
break;
}
}
3 years ago
}
}
4 weeks ago
// 如果没有找到匹配的元素集合set为null
if (!set) {
// 判断上下文对象是否有getElementsByTagName方法用于在非XML文档环境下获取所有标签名为*(也就是所有元素)的元素集合),如果有则调用该方法获取所有元素,否则返回空数组
set = typeof context.getElementsByTagName!== "undefined"?
context.getElementsByTagName("*") :
[];
}
3 years ago
4 weeks ago
// 返回一个包含找到的元素集合set以及剩余未处理的表达式expr的对象方便后续可能的进一步处理比如继续基于剩余表达式筛选元素等
return { set: set, expr: expr };
};
3 years ago
Sizzle.filter = function( expr, set, inplace, not ) {
var match, anyFound,
type, found, item, filter, left,
i, pass,
old = expr,
result = [],
curLoop = set,
isXMLFilter = set && set[0] && Sizzle.isXML( set[0] );
while ( expr && set.length ) {
for ( type in Expr.filter ) {
if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) {
filter = Expr.filter[ type ];
left = match[1];
anyFound = false;
match.splice(1,1);
if ( left.substr( left.length - 1 ) === "\\" ) {
continue;
}
if ( curLoop === result ) {
result = [];
}
if ( Expr.preFilter[ type ] ) {
match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );
if ( !match ) {
anyFound = found = true;
} else if ( match === true ) {
continue;
}
}
if ( match ) {
for ( i = 0; (item = curLoop[i]) != null; i++ ) {
if ( item ) {
found = filter( item, match, i, curLoop );
pass = not ^ found;
if ( inplace && found != null ) {
if ( pass ) {
anyFound = true;
} else {
curLoop[i] = false;
}
} else if ( pass ) {
result.push( item );
anyFound = true;
}
}
}
}
if ( found !== undefined ) {
if ( !inplace ) {
curLoop = result;
}
expr = expr.replace( Expr.match[ type ], "" );
if ( !anyFound ) {
return [];
}
break;
}
}
}
// Improper expression
if ( expr === old ) {
if ( anyFound == null ) {
Sizzle.error( expr );
} else {
break;
}
}
old = expr;
}
return curLoop;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
/**
* Utility function for retreiving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
var getText = Sizzle.getText = function( elem ) {
var i, node,
nodeType = elem.nodeType,
ret = "";
if ( nodeType ) {
if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent || innerText for elements
if ( typeof elem.textContent === 'string' ) {
return elem.textContent;
} else if ( typeof elem.innerText === 'string' ) {
// Replace IE's carriage returns
return elem.innerText.replace( rReturn, '' );
} else {
// Traverse it's children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
} else {
// If no nodeType, this is expected to be an array
for ( i = 0; (node = elem[i]); i++ ) {
// Do not traverse comment nodes
if ( node.nodeType !== 8 ) {
ret += getText( node );
}
}
}
return ret;
};
4 weeks ago
// 定义Expr对象它包含选择器引擎的一些核心属性和方法Sizzle.selectors将其引用为Expr
var Expr = Sizzle.selectors = {
// 定义选择器匹配的优先级顺序
order: [ "ID", "NAME", "TAG" ],
// 定义一个对象,包含不同类型的选择器匹配正则表达式
match: {
// ID选择器匹配以#开头的字符串后面跟随一个或多个字母、数字、连字符、Unicode字符或转义字符
ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
// 类选择器,匹配以.开头的字符串后面跟随一个或多个字母、数字、连字符、Unicode字符或转义字符
CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
// 名称选择器,匹配[name='value']的形式其中value可以是字母、数字、连字符、Unicode字符或转义字符
NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,
// 属性选择器,匹配[attr=value]的形式,支持多种属性值和复杂的表达式
ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,
// 标签选择器匹配一个或多个字母、数字、星号、连字符、Unicode字符或转义字符
TAG: /^((?:[\w\u00c0-\uFFFF*\-]|\\.)+)/,
// 子选择器,匹配:first-child, :last-child, :nth-child(n), :only-child等
CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,
// 位置选择器,匹配:nth, :eq, :gt, :lt, :first, :last, :even, :odd等
POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,
// 伪类选择器,匹配形如:hover, :focus等的伪类支持带参数的伪类如:not(.class)
PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/
3 years ago
},
4 weeks ago
// leftMatch对象可能用于存储一些预处理或解析过程中使用的匹配信息
leftMatch: {},
3 years ago
4 weeks ago
// attrMap对象定义了一些属性名的映射用于处理某些HTML属性在DOM中的不同表示
attrMap: {
"class": "className",
// class属性在DOM中对应className
"for": "htmlFor"
// for属性在DOM中对应htmlFor
},
3 years ago
4 weeks ago
// attrHandle对象定义了一些特定属性的处理函数
attrHandle: {
// href属性的处理函数返回元素的href属性值
href: function( elem ) {
return elem.getAttribute( "href" );
},
// type属性的处理函数返回元素的type属性值
type: function( elem ) {
return elem.getAttribute( "type" );
3 years ago
}
},
4 weeks ago
// 定义一个对象,包含处理相对选择器的函数
relative: {
// "+" 选择器的处理函数,用于查找当前元素之前的相邻兄弟元素
"+": function(checkSet, part){
// 判断part是否为字符串类型
var isPartStr = typeof part === "string",
// 判断part是否为标签名即不包含非单词字符
isTag = isPartStr && !rNonWord.test( part ),
// 判断part是否为字符串但不是标签名可能是一个类名、ID等
isPartStrNotTag = isPartStr && !isTag;
// 如果part是标签名则将其转换为小写
if ( isTag ) {
part = part.toLowerCase();
3 years ago
}
4 weeks ago
// 遍历checkSet中的每个元素
for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
// 获取当前遍历到的元素
if ( (elem = checkSet[i]) ) {
// 向上遍历前一个兄弟元素直到找到一个元素节点nodeType为1或没有兄弟元素为止
while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}
// 根据条件更新checkSet[i]的值
// 如果part不是标签名或者elem存在且其标签名与part小写相同则设置为elem或false如果elem不存在
// 如果part是具体的某个元素通过===比较则直接比较elem和part是否相同
checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ?
elem || false :
// 如果条件满足设置为elem如果存在或false如果不存在
elem === part;
// 如果part是具体的元素直接比较是否相等
}
}
3 years ago
4 weeks ago
// 如果part是字符串但不是标签名可能是一个类名、ID等则调用Sizzle的filter函数来处理
if ( isPartStrNotTag ) {
Sizzle.filter( part, checkSet, true );
3 years ago
}
4 weeks ago
// “>” 选择器的处理函数,用于查找当前元素的直接子元素
},
">": function( checkSet, part ) {
var elem,
// 当前遍历到的元素
isPartStr = typeof part === "string",
// 判断part是否为字符串类型
i = 0,
// 循环计数器
l = checkSet.length;
// checkSet的长度
// 如果part是字符串且不包含非单词字符可能是标签名则进行以下处理
if ( isPartStr && !rNonWord.test( part ) ) {
part = part.toLowerCase();
// 将part转换为小写以确保比较时不区分大小写
// 遍历checkSet中的每个元素
for ( ; i < l; i++ ) {
elem = checkSet[i];
// 获取当前遍历到的元素
if ( elem ) {
var parent = elem.parentNode;
// 获取当前元素的父元素
// 如果当前元素的父元素的标签名与part小写相同则将该父元素设置为checkSet[i]的值否则设置为false
checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false;
}
}
// 注意这里的代码片段没有包含rNonWord正则表达式的定义也没有包含函数的结束括号和对象字面量的结束花括号。
} // 如果part不是简单的标签名即包含非单词字符或未定义rNonWord导致的其他情况
else {
// 遍历checkSet中的每个元素
for (; i < l; i++) {
elem = checkSet[i];
// 获取当前遍历到的元素
if (elem) {
// 根据part是否为字符串类型更新checkSet[i]的值
// 如果是字符串则保留elem的父元素如果不是可能是具体的DOM元素则比较elem的父元素是否等于part
checkSet[i] = isPartStr ?
elem.parentNode :
// 如果part是字符串则设置为elem的父元素
elem.parentNode === part;
// 如果part不是字符串可能是DOM元素则比较elem的父元素是否等于part
}
}
3 years ago
4 weeks ago
// 如果part是字符串类型则对checkSet进行进一步的筛选
// 这可能是为了处理类名、ID或其他属性选择器的情况
if (isPartStr) {
Sizzle.filter(part, checkSet, true);
// 调用Sizzle的filter函数进行筛选true可能是表示某种特定行为的标志
}
}
},
// 注意:这里的代码片段是“>”选择器的处理函数的一部分,并且没有包含函数的结束括号和对象字面量的结束花括号。
// 此外还假设了Sizzle.filter函数的存在和行为以及isPartStr、checkSet、part、i和l等变量的上下文。
// 定义一个对象字面量,其中包含不同选择器的处理函数
3 years ago
4 weeks ago
// 空字符串选择器的处理函数
3 years ago
"": function(checkSet, part, isXML){
4 weeks ago
var nodeCheck,
// 用于存储节点检查的变量(可能是标签名)
doneName = done++,
// 一个唯一标识符,可能用于跟踪检查过程的状态,`done`可能是一个外部变量,在此函数中自增
checkFn = dirCheck;
// 初始检查函数可能用于执行一般的DOM树遍历和检查
// 如果part是字符串且不包含非单词字符则进行以下处理
if ( typeof part === "string" && !rNonWord.test( part ) ) {
part = part.toLowerCase();
// 将part转换为小写
nodeCheck = part;
// 将part设置为nodeCheck用于后续的节点检查
checkFn = dirNodeCheck;
// 将检查函数更改为dirNodeCheck可能用于基于节点名的检查
}
// 调用检查函数,传入相关参数以执行检查逻辑
// "parentNode"表示要检查的DOM关系在这个上下文中可能是用于遍历父元素
// part、doneName、checkSet、nodeCheck和isXML是其他必要的参数
checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML );
},
3 years ago
4 weeks ago
// 波浪线选择器(~)的处理函数,用于选择同一父元素下的兄弟元素
3 years ago
"~": function( checkSet, part, isXML ) {
4 weeks ago
var nodeCheck, // 同上,用于存储节点检查的变量
doneName = done++,
// 同上,生成一个唯一标识符
checkFn = dirCheck;
// 同上,初始检查函数
// 如果part是字符串且不包含非单词字符则进行与空字符串选择器相同的处理
if ( typeof part === "string" && !rNonWord.test( part ) ) {
part = part.toLowerCase();
// 转换为小写
nodeCheck = part;
// 设置为nodeCheck
checkFn = dirNodeCheck;
// 更改检查函数为dirNodeCheck
}
// 调用检查函数,但这次传入"previousSibling"作为要检查的DOM关系
// 这表明我们是在查找同一父元素下的前一个兄弟元素(但实际上可能是通过逻辑来查找所有匹配的兄弟元素)
// 注意:这里的实现细节可能有所不同,因为波浪线选择器通常需要检查所有兄弟元素,而不仅仅是前一个
checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML );
}
3 years ago
},
4 weeks ago
// 注意:这里的代码片段没有包含`done`变量的定义、`dirCheck`和`dirNodeCheck`函数的定义,以及对象字面量的结束花括号。
// 这些都是在外部定义的,可能是选择器引擎的一部分。
3 years ago
4 weeks ago
find: {
// ID选择器函数用于根据元素的ID查找元素
ID: function( match, context, isXML ) {
// 如果上下文对象context有getElementById方法并且不是在XML文档中
if ( typeof context.getElementById !== "undefined" && !isXML ) {
// 使用getElementById方法获取匹配的元素
var m = context.getElementById(match[1]);
// 检查获取到的元素是否有父节点以处理Blackberry 4.6返回的不在文档中的节点的问题
// #6963是一个可能是相关的bug编号
return m && m.parentNode ? [m] : [];
3 years ago
}
4 weeks ago
},
3 years ago
4 weeks ago
// NAME选择器函数用于根据元素的name属性查找元素
NAME: function( match, context ) {
// 如果上下文对象context有getElementsByName方法
if ( typeof context.getElementsByName !== "undefined" ) {
// 初始化一个空数组,用于存储匹配的结果
var ret = [],
// 使用getElementsByName方法获取所有name属性匹配的元素
results = context.getElementsByName(match[1]);
// 遍历所有获取到的元素
for (var i = 0, l = results.length; i < l; i++) {
// 如果元素的name属性确实匹配查找的值
if (results[i].getAttribute("name") === match[1]) {
// 将该元素添加到结果数组中
ret.push(results[i]);
3 years ago
}
}
4 weeks ago
// 如果没有找到任何匹配的元素返回null否则返回结果数组
return ret.length === 0 ? null : ret;
}
3 years ago
}
4 weeks ago
},
3 years ago
4 weeks ago
TAG: function( match, context ) {
// 如果上下文对象context有getElementsByTagName方法
if ( typeof context.getElementsByTagName !== "undefined" ) {
// 使用getElementsByTagName方法查找所有匹配的标签名元素并返回结果数组
return context.getElementsByTagName( match[1] );
}
},
// 预处理过滤器对象,用于在正式查找前对选择器进行一些处理
preFilter: {
// CLASS过滤器函数用于处理类名选择器
CLASS: function( match, curLoop, inplace, result, not, isXML ) {
// 对match[1]类名字符串进行处理去除可能的反斜杠这里rBackslash应该是一个正则表达式
// 并在类名字符串的前后加上空格,这通常是为了处理类名选择器时的边界情况
match = " " + match[1].replace( rBackslash, "" ) + " ";
// 如果是在XML文档中则直接返回处理后的类名字符串
// 这里的处理可能是为了后续在XML环境中进行特定的匹配
if ( isXML ) {
return match;
}
// 注意:此代码段在此处被截断,没有显示后续的处理逻辑
// 通常情况下这里会有更多的代码来处理类名选择器尤其是在非XML环境中
// 遍历curLoop数组中的每个元素直到elem为null
for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
// 如果elem不是假值即elem是一个有效的DOM元素
if ( elem ) {
// 检查elem的className是否包含match指定的类名
// not是一个布尔值用于指示是否进行反向匹配即排除具有该类名的元素
// ^ 是位异或运算符,但在这里它可能是一个逻辑错误,因为通常我们会用!或==/!=来比较布尔值
// 正确的逻辑可能是使用!或==来根据not的值决定是包含还是排除类名
// elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0
// 这段代码首先确保elem有className然后将className前后加上空格并替换掉所有的制表符、换行符和回车符最后检查处理后的字符串中是否包含match指定的类名
if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) {
// 如果不在inplace模式下并且元素匹配或根据not的值应该被包含则将元素添加到结果集中
if ( !inplace ) {
result.push( elem );
}
3 years ago
4 weeks ago
} else if ( inplace ) {
// 如果在inplace模式下并且元素不匹配或根据not的值应该被排除则将当前元素在curLoop中的位置设置为false
// 这意味着在后续的迭代中,这个元素将被跳过
curLoop[i] = false;
}
}
3 years ago
}
4 weeks ago
// 函数返回false这可能表示在当前的处理逻辑下没有特殊的返回值需要传递给调用者
// 或者这可能是一个约定俗成的返回值,用于指示某种状态或条件
3 years ago
return false;
4 weeks ago
},
3 years ago
4 weeks ago
// ID选择器处理函数
ID: function( match ) {
// 从match数组中提取ID值并去除可能的反斜杠字符然后返回处理后的ID字符串
return match[1].replace( rBackslash, "" );
},
3 years ago
4 weeks ago
// TAG选择器处理函数
TAG: function( match, curLoop ) {
// 从match数组中提取标签名去除可能的反斜杠字符并将其转换为小写然后返回处理后的标签名字符串
// 注意尽管这个函数接收了curLoop参数但在当前代码段中并没有使用它
return match[1].replace( rBackslash, "" ).toLowerCase();
},
3 years ago
4 weeks ago
// CHILD选择器处理函数用于处理如:nth-child之类的伪类选择器
CHILD: function( match ) {
// 如果匹配的是nth类型的子选择器
if ( match[1] === "nth" ) {
// 如果没有提供nth的具体参数如2n+1则抛出错误
if ( !match[2] ) {
Sizzle.error( match[0] );
}
3 years ago
4 weeks ago
// 去除nth参数前的加号或空格
match[2] = match[2].replace(/^\+|\s*/g, '');
// 使用正则表达式解析nth参数支持'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'等形式的表达式
var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec(
match[2] === "even" && "2n" ||
// 如果是'even',则转换为'2n'
match[2] === "odd" && "2n+1" ||
// 如果是'odd',则转换为'2n+1'
!/\D/.test( match[2] ) && "0n+" + match[2] ||
// 如果是一个纯数字,则前面加上'0n+'
match[2]
// 如果都不匹配则直接使用原始match[2]
);
// 计算nth参数中的系数和偏移量包括处理负数的情况
// test[1]是符号(+或-test[2]是系数可能是空字符串表示默认为1test[3]是偏移量
match[2] = (test[1] + (test[2] || 1)) - 0; // 系数,确保是数字类型
match[3] = test[3] - 0;
// 偏移量,确保是数字类型
}
// 如果不是nth类型的子选择器但提供了第二个参数通常不应该则抛出错误
else if ( match[2] ) {
Sizzle.error( match[0] );
}
// 注意函数没有返回值因为它可能是通过修改match数组来影响外部状态的
3 years ago
4 weeks ago
// TODO: 这是一个待办事项,表示需要将这部分代码移动到正常的缓存系统中去
// 这可能是指优化性能,通过缓存某些计算结果来避免重复计算
match[0] = done++;
// 将match数组的第一个元素设置为一个递增的计数器值可能用于标识处理进度或唯一性
3 years ago
4 weeks ago
return match;
// 返回处理后的match数组
},
3 years ago
4 weeks ago
// ATTR选择器处理函数用于处理属性选择器如[attr=value]
ATTR: function( match, curLoop, inplace, result, not, isXML ) {
// 从match数组中提取属性名并去除可能的反斜杠字符
var name = match[1] = match[1].replace( rBackslash, "" );
3 years ago
4 weeks ago
// 如果不是在XML上下文中并且Expr.attrMap中存在该属性名的映射
// 则将属性名替换为映射后的名称这通常用于处理HTML中的特殊属性
if ( !isXML && Expr.attrMap[name] ) {
match[1] = Expr.attrMap[name];
}
3 years ago
4 weeks ago
// 处理未使用引号括起来的值(如果有的话)
// 这通常是为了确保属性值中的特殊字符被正确处理
match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" );
3 years ago
4 weeks ago
// 如果使用的是~=运算符(表示“包含一个单词”的匹配)
// 则在属性值的前后各添加一个空格,以确保单词边界的正确匹配
if ( match[2] === "~=" ) {
match[4] = " " + match[4] + " ";
}
3 years ago
4 weeks ago
// 返回处理后的match数组
return match;
},
// PSEUDO函数用于处理伪类选择器
PSEUDO: function( match, curLoop, inplace, result, not ) {
// 检查是否处理的是:not伪类
if ( match[1] === "not" ) {
// 如果:not内部包含复杂的表达式或简单的单词表达式
// 使用chunker正则表达式来分割和解析表达式或者检查表达式是否以单词字符开头
if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) {
// 对:not内部的表达式进行完整的Sizzle查询
// 注意这里假设chunker是一个能够解析复杂选择器的正则表达式
// null参数可能表示在当前的文档或上下文中进行查询
match[3] = Sizzle(match[3], null, null, curLoop);
3 years ago
4 weeks ago
} else {
// 如果:not内部是一个简单的选择器则使用Sizzle.filter进行过滤
var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
3 years ago
4 weeks ago
// 如果不是就地修改结果集
if ( !inplace ) {
// 将过滤后的结果添加到最终的结果集中
result.push.apply( result, ret );
}
3 years ago
4 weeks ago
// 返回false表示这个分支已经处理了结果不需要进一步处理
return false;
}
3 years ago
4 weeks ago
// 检查是否处理的是位置伪类(如:first-child或其他Expr.match.POS定义的伪类
} else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
// 返回true表示这个选择器需要特殊处理可能是由其他部分的代码处理
return true;
}
3 years ago
4 weeks ago
// 如果没有特别处理则返回原始的match数组
return match;
},
// POS函数可能用于处理位置伪类选择器如:first-child, :last-child等
// 但这里的实现看起来有些简单只是向match数组中添加了一个true值
POS: function( match ) {
match.unshift(true);
// 在match数组的开头添加一个true值可能表示这个选择器需要特殊处理
return match;
// 返回修改后的match数组
}
},
3 years ago
4 weeks ago
// filters对象包含一系列用于过滤DOM元素的函数
filters: {
// enabled函数用于检查元素是否启用即不是disabled状态且type不是hidden
enabled: function( elem ) {
return elem.disabled === false && elem.type !== "hidden";
// 如果元素没有被禁用且type属性不是"hidden"则返回true
},
3 years ago
4 weeks ago
// disabled函数用于检查元素是否被禁用
disabled: function( elem ) {
return elem.disabled === true;
// 如果元素的disabled属性为true则返回true
},
3 years ago
4 weeks ago
// checked函数用于检查元素是否被选中通常用于checkbox和radio按钮
checked: function( elem ) {
return elem.checked === true;
// 如果元素的checked属性为true则返回true
},
3 years ago
4 weeks ago
// selected函数用于检查元素是否被选中通常用于<option>元素)
// 注意在Safari中对于默认选中的<option>直接访问selected属性可能不会返回正确的值
// 因此这里先访问parentNode的selectedIndex属性来“触发”正确的选中状态
selected: function( elem ) {
if ( elem.parentNode ) {
// 如果元素有父节点
elem.parentNode.selectedIndex;
// 访问父节点的selectedIndex属性这是一个“技巧”来确保Safari正确处理默认选中的<option>
}
3 years ago
4 weeks ago
return elem.selected === true;
// 如果元素的selected属性为true则返回true
},
3 years ago
4 weeks ago
// filters对象继续定义包含一系列用于过滤DOM元素的函数
// parent函数检查元素是否有子元素
parent: function( elem ) {
return !!elem.firstChild;
// 如果元素有firstChild属性即至少有一个子节点则返回true
},
// empty函数检查元素是否为空即没有子元素
empty: function( elem ) {
return !elem.firstChild;
// 如果元素没有firstChild属性即没有子节点则返回true
},
// has函数检查元素是否包含与给定选择器匹配的子元素
has: function( elem, i, match ) {
return !!Sizzle( match[3], elem ).length;
// 使用Sizzle选择器在元素内查找与match[3]匹配的子元素如果找到则返回true
},
// header函数检查元素是否为标题元素h1-h6
header: function( elem ) {
return (/h\d/i).test( elem.nodeName );
// 使用正则表达式检查元素的nodeName是否以"h"开头并跟着一个数字(不区分大小写)
},
// text函数检查元素是否为文本类型的<input>元素
text: function( elem ) {
var attr = elem.getAttribute( "type" ), type = elem.type;
// 对于新的HTML5输入类型如searchIE6和7可能会将elem.type映射为'text'
// 因此使用getAttribute来检查原始的type属性
return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null ); // 检查元素是否为<input>且type为'text'同时确保原始的type属性也是'text'或未设置
},
// radio函数检查元素是否为单选按钮<input type="radio">
radio: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type;
// 检查元素是否为<input>且type为'radio'
},
// checkbox函数检查元素是否为复选框<input type="checkbox">
checkbox: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type;
// 检查元素是否为<input>且type为'checkbox'
},
// file函数检查元素是否为文件选择框<input type="file">
file: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "file" === elem.type;
// 检查元素是否为<input>且type为'file'
},
// password函数检查元素是否为密码框<input type="password">
password: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "password" === elem.type;
// 检查元素是否为<input>且type为'password'
},
// submit函数检查元素是否为提交按钮<input type="submit">或<button type="submit">
submit: function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && "submit" === elem.type;
// 检查元素是否为<input>或<button>且type为'submit'
},
// image函数检查元素是否为图像按钮<input type="image">
image: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "image" === elem.type;
// 检查元素是否为<input>且type为'image'
},
// reset函数检查元素是否为重置按钮<input type="reset">或<button type="reset">
reset: function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && "reset" === elem.type;
// 检查元素是否为<input>或<button>且type为'reset'
},
// button函数检查元素是否为按钮<input type="button">或<button>
button: function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && "button" === elem.type || name === "button";
// 检查元素是否为<input type="button">或<button>
},
// input函数检查元素是否为输入元素<input>、<select>、<textarea>或<button>
input: function( elem ) {
return (/input|select|textarea|button/i).test( elem.nodeName );
// 使用正则表达式检查元素的nodeName是否为<input>、<select>、<textarea>或<button>(不区分大小写)
},
// focus函数检查元素是否为当前文档中获得焦点的元素
focus: function( elem ) {
return elem === elem.ownerDocument.activeElement;
// 检查元素是否等于其所属文档的activeElement属性即当前获得焦点的元素
}
},
// 定义一个对象包含多个用于筛选DOM元素的函数
setFilters: {
// 筛选第一个元素
first: function( elem, i ) {
return i === 0;
// 如果当前索引为0则返回true表示这是第一个元素
},
3 years ago
4 weeks ago
// 筛选最后一个元素
last: function( elem, i, match, array ) {
return i === array.length - 1;
// 如果当前索引等于数组长度减1则返回true表示这是最后一个元素
},
3 years ago
4 weeks ago
// 筛选偶数索引的元素
even: function( elem, i ) {
return i % 2 === 0;
// 如果当前索引除以2的余数为0则返回true表示这是偶数索引的元素
},
3 years ago
4 weeks ago
// 筛选奇数索引的元素
odd: function( elem, i ) {
return i % 2 === 1;
// 如果当前索引除以2的余数为1则返回true表示这是奇数索引的元素
},
3 years ago
4 weeks ago
// 筛选小于给定值的索引的元素
lt: function( elem, i, match ) {
return i < match[3] - 0;
// 如果当前索引小于match[3]转换为数字的值则返回true
},
3 years ago
4 weeks ago
// 筛选大于给定值的索引的元素
gt: function( elem, i, match ) {
return i > match[3] - 0;
// 如果当前索引大于match[3]转换为数字的值则返回true
},
3 years ago
4 weeks ago
// 筛选等于给定值的索引的元素
nth: function( elem, i, match ) {
return match[3] - 0 === i;
// 如果当前索引等于match[3]转换为数字的值则返回true
},
3 years ago
4 weeks ago
// 筛选等于给定值的索引的元素与nth相同
eq: function( elem, i, match ) {
return match[3] - 0 === i;
// 如果当前索引等于match[3]转换为数字的值则返回true
3 years ago
}
4 weeks ago
},
3 years ago
4 weeks ago
// 定义一个对象,包含处理伪类选择器的函数
filter: {
PSEUDO: function( elem, match, i, array ) {
var name = match[1], // 获取伪类选择器的名称
filter = Expr.filters[ name ];
// 尝试从Expr.filters对象中获取对应的筛选函数
if ( filter ) {
return filter( elem, i, match, array );
// 如果找到了筛选函数,则调用它
} else if ( name === "contains" ) {
// 如果伪类选择器是"contains",则检查元素的文本内容是否包含给定的字符串
return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0;
} else if ( name === "not" ) {
// 如果伪类选择器是"not",则检查元素是否不在给定的集合中
var not = match[3];
for ( var j = 0, l = not.length; j < l; j++ ) {
if ( not[j] === elem ) {
return false;
// 如果元素在给定的集合中则返回false
}
}
return true;
// 如果元素不在给定的集合中则返回true
3 years ago
} else {
Sizzle.error( name );
}
},
4 weeks ago
// 定义一个处理子选择器的函数
CHILD: function( elem, match ) {
// 声明一系列变量,用于在函数内部使用
var first, last,
doneName, parent, cache,
count, diff,
// 从match数组中获取子选择器的类型如"only", "first", "last", "nth"
type = match[1],
// 将elem赋值给node变量作为当前操作的节点
node = elem;
// 使用switch语句根据子选择器的类型执行不同的逻辑
switch (type) {
// 处理":only-child"和":first-child"选择器
case "only":
case "first":
// 循环遍历当前节点的前一个兄弟节点
while ((node = node.previousSibling)) {
// 如果找到一个元素节点nodeType === 1
if (node.nodeType === 1) {
// 对于":first-child"来说如果找到前一个兄弟元素节点则返回false
// 对于":only-child"来说,这个判断也会阻止进一步的处理,但逻辑会继续到下面的"falls through"部分
return false;
}
3 years ago
}
4 weeks ago
// 如果到达这里,说明当前节点是第一个子节点(对于":first-child"
if (type === "first") {
return true;
}
3 years ago
4 weeks ago
// 重置node变量为elem因为对于":only-child"来说,我们还需要检查后面是否有兄弟节点
node = elem;
3 years ago
4 weeks ago
/* falls through */ // 如果没有break语句代码将继续执行到下一个case这是JavaScript中的"贯穿"特性
3 years ago
4 weeks ago
// 处理":last-child"选择器
case "last":
// 循环遍历当前节点的下一个兄弟节点
while ((node = node.nextSibling)) {
// 如果找到一个元素节点nodeType === 1
if (node.nodeType === 1) {
// 如果找到后一个兄弟元素节点则返回false
return false;
}
}
3 years ago
4 weeks ago
// 如果到达这里,说明当前节点是最后一个子节点
return true;
3 years ago
4 weeks ago
// 处理":nth-child"选择器
case "nth":
// 从match数组中获取"nth"选择器的参数(如"2n+1"的解析结果这里假设first是alast是b对于"an+b"的形式)
first = match[2];
last = match[3];
3 years ago
4 weeks ago
// 如果first是1且last是0这实际上表示":first-child"的情况(但这里可能是为了处理更复杂的"nth"逻辑而做的简化判断)
// 注意:这个判断可能不完全准确,因为真正的":nth-child(1)"应该考虑索引从1开始而这里的逻辑可能是基于0索引的简化
if (first === 1 && last === 0) {
return true;
}
// 注意:此代码段在这里被截断,对于":nth-child"的完整处理逻辑应该包括计算当前元素的索引并根据first和last的值来判断是否匹配
// 注意:函数在这里结束,但对于":nth-child"等复杂情况的处理逻辑并未完全展示
// 定义一个对象,包含不同的选择器匹配函数
doneName = match[0];
// 获取当前元素的父节点
parent = elem.parentNode;
// 如果父节点存在且父节点上没有存储过处理过的标记或当前元素没有索引
if ( parent && (parent[ expando ] !== doneName || !elem.nodeIndex) ) {
// 初始化计数器
count = 0;
// 遍历父节点的所有子节点
for ( node = parent.firstChild; node; node = node.nextSibling ) {
// 如果节点是元素节点
if ( node.nodeType === 1 ) {
// 为元素节点分配一个索引
node.nodeIndex = ++count;
}
}
3 years ago
4 weeks ago
// 在父节点上存储处理过的标记
parent[ expando ] = doneName;
}
3 years ago
4 weeks ago
// 计算当前元素的索引与":nth-child"参数中的last的差异
diff = elem.nodeIndex - last;
3 years ago
4 weeks ago
// 如果first为0则检查diff是否为0可能是处理":nth-of-type(0n+1)"的简化情况)
if ( first === 0 ) {
return diff === 0;
3 years ago
4 weeks ago
// 否则,根据":nth-child"的规则检查是否匹配
} else {
// 检查diff是否能被first整除且结果非负
return (diff % first === 0 && diff / first >= 0);
}
}
},
// ":id" 选择器匹配函数
ID: function( elem, match ) {
// 如果元素是元素节点且其id属性与选择器匹配
return elem.nodeType === 1 && elem.getAttribute("id") === match;
},
// ":tag" 选择器匹配函数
TAG: function( elem, match ) {
// 如果选择器是"*"或元素节点名称与选择器匹配(不区分大小写)
return (match === "*" && elem.nodeType === 1) || !!elem.nodeName && elem.nodeName.toLowerCase() === match;
},
// ":class" 选择器匹配函数
CLASS: function( elem, match ) {
// 检查元素的className或class属性中是否包含选择器指定的类名
return (" " + (elem.className || elem.getAttribute("class")) + " ")
.indexOf( match ) > -1;
},
// "[attribute]" 选择器匹配函数
ATTR: function( elem, match ) {
// ...(此函数内部逻辑较复杂,省略详细注释,但大致是根据属性名和值进行匹配)
// ...
},
// ":position" 选择器匹配函数(如":first", ":last", ":even", ":odd"等伪类)
POS: function( elem, match, i, array ) {
// 根据选择器名称获取对应的过滤函数
var name = match[2],
filter = Expr.setFilters[ name ];
// 如果存在过滤函数,则调用它进行匹配
if ( filter ) {
return filter(elem, i, match, array);
}
}
}
// ...(其他代码省略)
};
// 定义一个正则表达式替换函数,用于在正则表达式中转义数字
var fescape = function(all, num){
return "\\" + (num - 0 + 1);
// 注意这里的num-0+1可能是为了确保num是数字并转换为字符串后加1但在这个上下文中看起来有些多余
};
// 遍历Expr.match中的每个选择器类型
for ( var type in Expr.match ) {
// 为每个选择器类型构造一个新的正则表达式,添加额外的括号匹配逻辑
Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) );
// 为每个选择器类型构造左匹配的正则表达式,并替换数字引用
Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) );
}
3 years ago
4 weeks ago
// 暴露原始的POS匹配逻辑
Expr.match.globalPOS = origPOS;
3 years ago
4 weeks ago
// 定义一个函数,用于将类数组对象转换为真正的数组,并可选择地将结果添加到另一个数组中
var makeArray = function( array, results ) {
// 使用Array.prototype.slice将类数组对象转换为数组
array = Array.prototype.slice.call( array, 0 );
3 years ago
4 weeks ago
// 如果提供了results数组则将转换后的数组元素添加到results中
if ( results ) {
results.push.apply( results, array );
return results;
}
3 years ago
4 weeks ago
// 如果没有提供results数组则直接返回转换后的数组
return array;
};
3 years ago
// Perform a simple check to determine if the browser is capable of
// converting a NodeList to an array using builtin methods.
// Also verifies that the returned array holds DOM nodes
// (which is not the case in the Blackberry browser)
4 weeks ago
try {
// 尝试使用Array.prototype.slice.call来转换document.documentElement.childNodes为数组并获取第一个子节点的nodeType
Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType;
3 years ago
4 weeks ago
// 如果上面的代码执行失败,则提供一个备选方法
} catch( e ) {
// 定义一个makeArray函数用于将类数组对象转换为真正的数组
makeArray = function( array, results ) {
var i = 0,
ret = results || [];
// 初始化结果数组,默认为空数组
3 years ago
4 weeks ago
// 如果传入的array是真正的数组
if ( toString.call(array) === "[object Array]" ) {
Array.prototype.push.apply( ret, array );
// 使用push.apply将array的元素添加到ret数组中
3 years ago
} else {
4 weeks ago
// 如果array有length属性可能是类数组对象
if ( typeof array.length === "number" ) {
for ( var l = array.length; i < l; i++ ) {
ret.push( array[i] );
// 遍历array将元素添加到ret数组中
}
} else {
// 如果array没有length属性则遍历直到array[i]为undefined
for ( ; array[i]; i++ ) {
ret.push( array[i] );
// 将元素添加到ret数组中
}
3 years ago
}
}
4 weeks ago
return ret;
// 返回转换后的数组
};
}
3 years ago
4 weeks ago
var sortOrder, siblingCheck;
// 声明两个变量sortOrder用于排序siblingCheck用于比较兄弟节点
3 years ago
4 weeks ago
// 如果浏览器支持compareDocumentPosition方法
if ( document.documentElement.compareDocumentPosition ) {
sortOrder = function( a, b ) {
// 如果两个节点相同则标记有重复并返回0
if ( a === b ) {
hasDuplicate = true;
return 0;
}
3 years ago
4 weeks ago
// 如果其中一个节点不支持compareDocumentPosition方法
if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) {
// 返回支持compareDocumentPosition方法的节点为-1另一个为1这里逻辑可能有误通常应该返回不支持的节点为-1
return a.compareDocumentPosition ? -1 : 1;
}
3 years ago
4 weeks ago
// 使用compareDocumentPosition方法比较节点位置如果a在b之前返回-1否则返回1
return a.compareDocumentPosition(b) & 4 ? -1 : 1;
};
3 years ago
4 weeks ago
} else {
// 如果浏览器不支持compareDocumentPosition方法则使用备选方案
sortOrder = function (a, b) {
// 如果两个节点相同则标记有重复并返回0
if (a === b) {
hasDuplicate = true;
return 0;
// 如果两个节点都有sourceIndex属性IE特有
} else if (a.sourceIndex && b.sourceIndex) {
// 使用sourceIndex属性比较节点位置
return a.sourceIndex - b.sourceIndex;
}
var al, bl,
ap = [],
bp = [],
aup = a.parentNode,
bup = b.parentNode,
cur = aup;
// 如果两个节点的父节点相同,则进行兄弟节点比较
if (aup === bup) {
return siblingCheck(a, b);
// 如果a没有父节点则a在文档树中位置更靠后返回-1
} else if (!aup) {
return -1;
3 years ago
4 weeks ago
// 如果b没有父节点则b在文档树中位置更靠后返回1
} else if (!bup) {
return 1;
}
3 years ago
4 weeks ago
// 否则,需要构建两个节点的父节点链进行比较
while (cur) {
ap.unshift(cur);
// 将a的父节点添加到ap数组的前面
cur = cur.parentNode;
}
3 years ago
4 weeks ago
cur = bup;
3 years ago
4 weeks ago
while (cur) {
bp.unshift(cur);
// 将b的父节点添加到bp数组的前面
cur = cur.parentNode;
3 years ago
}
4 weeks ago
al = ap.length;
bl = bp.length;
3 years ago
4 weeks ago
// 从根节点开始,比较两个节点的父节点链,直到找到不同的父节点
for (var i = 0; i < al && i < bl; i++) {
if (ap[i] !== bp[i]) {
return siblingCheck(ap[i], bp[i]);
// 使用siblingCheck比较不同的父节点
}
}
3 years ago
4 weeks ago
// 如果遍历完所有父节点都没有找到不同的父节点,则比较兄弟节点
return i === al ?
siblingCheck(a, bp[i], -1) :
// a的父节点链更长a在b之前
siblingCheck(ap[i], b, 1);
// b的父节点链更长b在a之前
};
3 years ago
4 weeks ago
// 定义一个函数,用于检查两个元素是否是兄弟节点,并返回它们的相对位置
siblingCheck = function (a, b, ret) {
// 如果两个元素相同直接返回ret
if (a === b) {
return ret;
3 years ago
}
4 weeks ago
// 从a的下一个兄弟节点开始遍历
var cur = a.nextSibling;
3 years ago
4 weeks ago
// 循环遍历所有兄弟节点
while (cur) {
// 如果找到了b说明b在a的后面返回-1
if (cur === b) {
return -1;
}
3 years ago
4 weeks ago
// 继续检查下一个兄弟节点
cur = cur.nextSibling;
}
3 years ago
4 weeks ago
// 遍历结束仍未找到b说明b不在a的后面返回1
return 1;
};
}
3 years ago
4 weeks ago
// 检查浏览器在通过getElementById查询时是否返回具有相同name属性的元素并提供解决方案
(function(){
// 创建一个div元素用于测试
var form = document.createElement("div"),
// 生成一个唯一的id
id = "script" + (new Date()).getTime(),
// 获取文档的根元素
root = document.documentElement;
// 在form内部添加一个a元素name属性设置为生成的唯一id
form.innerHTML = "<a name='" + id + "'/>";
// 将form插入到文档的根元素的最前面
root.insertBefore( form, root.firstChild );
// 检查通过getElementById是否能找到这个a元素
// 如果能找到,说明浏览器存在这个问题,需要特殊处理
if ( document.getElementById( id ) ) {
// 修改Expr.find.ID方法增加额外的检查
Expr.find.ID = function( match, context, isXML ) {
// 如果上下文对象有getElementById方法且不是XML文档
if ( typeof context.getElementById !== "undefined" && !isXML ) {
var m = context.getElementById(match[1]);
// 如果找到了元素进一步检查id是否匹配或getAttributeNode返回的id值是否匹配
return m ?
m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ?
[m] :
// 如果匹配,返回包含该元素的数组
undefined :
// 如果不匹配返回undefined
[];
// 如果没有找到元素,返回空数组
}
};
3 years ago
4 weeks ago
// 修改Expr.filter.ID方法增加对元素id的验证
Expr.filter.ID = function( elem, match ) {
// 获取元素的id属性节点
var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
3 years ago
4 weeks ago
// 返回元素是元素节点且id值匹配的结果
return elem.nodeType === 1 && node && node.nodeValue === match;
};
3 years ago
}
4 weeks ago
// 移除之前插入的form元素
root.removeChild( form );
3 years ago
4 weeks ago
// 释放IE中的内存
root = form = null;
})();
3 years ago
4 weeks ago
(function(){
// 检查浏览器在使用getElementsByTagName("*")时是否只返回元素节点
3 years ago
4 weeks ago
// 创建一个div元素用于测试
var div = document.createElement("div");
// 在div中添加一个注释节点
div.appendChild( document.createComment("") );
3 years ago
4 weeks ago
// 检查通过getElementsByTagName("*")获取到的节点列表中是否包含注释节点
if ( div.getElementsByTagName("*").length > 0 ) {
// 如果包含注释节点修改Expr.find.TAG方法过滤掉注释节点
Expr.find.TAG = function( match, context ) {
var results = context.getElementsByTagName( match[1] );
3 years ago
4 weeks ago
// 如果匹配的是所有元素,则过滤掉非元素节点
if ( match[1] === "*" ) {
var tmp = [];
3 years ago
4 weeks ago
for ( var i = 0; results[i]; i++ ) {
if ( results[i].nodeType === 1 ) {
// 只保留元素节点
tmp.push( results[i] );
}
}
3 years ago
4 weeks ago
results = tmp;
// 更新结果列表
3 years ago
}
4 weeks ago
return results;
// 返回过滤后的结果
};
3 years ago
}
4 weeks ago
div.innerHTML = "<a href='#'></a>";
// 在div中添加一个a元素href属性设置为'#'
3 years ago
4 weeks ago
// 如果div的第一个子元素存在且该元素有getAttribute方法且通过getAttribute获取的href属性值不等于'#'
if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
div.firstChild.getAttribute("href") !== "#" ) {
3 years ago
4 weeks ago
// 则修改Expr.attrHandle.href方法使其通过getAttribute的第二个参数2来获取href属性的原始值不经过标准化处理
Expr.attrHandle.href = function( elem ) {
return elem.getAttribute( "href", 2 );
};
}
3 years ago
4 weeks ago
// 释放IE中的内存
div = null;
})();
// 如果浏览器支持querySelectorAll方法
if ( document.querySelectorAll ) {
(function(){
var oldSizzle = Sizzle,
// 保存原始的Sizzle函数
div = document.createElement("div"),
// 创建一个div元素用于测试
id = "__sizzle__";
// 定义一个用于测试的唯一ID
div.innerHTML = "<p class='TEST'></p>";
// 在div中添加一个p元素class属性设置为'TEST'
// Safari在quirks模式下无法正确处理大写或unicode字符如果querySelectorAll无法正确匹配则直接返回
if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
return;
}
3 years ago
4 weeks ago
// 重写Sizzle函数以支持querySelectorAll的优化
Sizzle = function( query, context, extra, seed ) {
context = context || document;
// 如果没有提供上下文则默认为document
3 years ago
4 weeks ago
// 只在非XML文档上使用querySelectorAllID选择器在非HTML文档中无效
if ( !seed && !Sizzle.isXML(context) ) {
// 尝试匹配简单的选择器以加速查询
var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query );
3 years ago
4 weeks ago
if ( match && (context.nodeType === 1 || context.nodeType === 9) ) {
// 优化如果选择器是标签名则使用getElementsByTagName
if ( match[1] ) {
return makeArray( context.getElementsByTagName( query ), extra );
3 years ago
4 weeks ago
// 优化如果选择器是类名且上下文支持getElementsByClassName则使用它
} else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) {
return makeArray( context.getElementsByClassName( match[2] ), extra );
}
}
3 years ago
4 weeks ago
if ( context.nodeType === 9 ) {
// 优化:如果选择器是"body"且上下文有body元素则直接返回body元素
if ( query === "body" && context.body ) {
return makeArray( [ context.body ], extra );
3 years ago
4 weeks ago
// 优化如果选择器是ID则使用getElementById
} else if ( match && match[3] ) {
var elem = context.getElementById( match[3] );
3 years ago
4 weeks ago
// 检查parentNode以确保元素仍在文档中Blackberry 4.6的问题)
if ( elem && elem.parentNode ) {
// 处理IE和Opera按名称而不是ID返回元素的情况
if ( elem.id === match[3] ) {
return makeArray( [ elem ], extra );
}
3 years ago
4 weeks ago
} else {
return makeArray( [], extra );
}
}
3 years ago
4 weeks ago
try {
// 尝试使用querySelectorAll
return makeArray( context.querySelectorAll(query), extra );
} catch(qsaError) {
// 如果querySelectorAll抛出错误则忽略并继续
}
3 years ago
4 weeks ago
// qSA在处理以元素为根的查询时表现奇怪
// 我们可以通过在根上指定一个额外的ID并从那里开始工作来绕过这个问题
// 感谢Andrew Dupont提供的技术
// IE 8在object元素上不起作用
} else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
var oldContext = context,
old = context.getAttribute( "id" ),
nid = old || id,
hasParent = context.parentNode,
relativeHierarchySelector = /^\s*[+~]/.test( query );
if ( !old ) {
// 如果上下文没有ID则为其设置一个唯一的ID
context.setAttribute( "id", nid );
} else {
// 如果上下文已有ID则对其进行转义以防止CSS注入
nid = nid.replace( /'/g, "\\$&" );
}
// 如果选择器包含层次选择器(+~),并且上下文有父节点,则将上下文更改为父节点
if ( relativeHierarchySelector && hasParent ) {
context = context.parentNode;
}
3 years ago
4 weeks ago
try {
// 尝试使用修改后的上下文和选择器进行查询
if ( !relativeHierarchySelector || hasParent ) {
return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra );
}
3 years ago
4 weeks ago
} catch(pseudoError) {
// 如果查询抛出错误,则忽略并继续
} finally {
// 无论是否成功最后都要移除之前设置的ID
if ( !old ) {
oldContext.removeAttribute( "id" );
}
}
}
3 years ago
}
4 weeks ago
// 如果以上优化都不适用则回退到使用原始的Sizzle函数
return oldSizzle(query, context, extra, seed);
};
3 years ago
for ( var prop in oldSizzle ) {
Sizzle[ prop ] = oldSizzle[ prop ];
}
// release memory in IE
div = null;
})();
}
4 weeks ago
// 定义一个自执行函数
(function(){
// 获取文档的根元素(通常是<html>
var html = document.documentElement,
// 尝试获取不同浏览器前缀下的matchesSelector方法
matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector;
if ( matches ) {
// 创建一个临时的div元素来检查在断开连接的节点上是否可以使用matchesSelectorIE9失败
var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ),
pseudoWorks = false;
3 years ago
4 weeks ago
try {
// 尝试一个应该失败的伪类选择器Gecko不报错返回false
matches.call( document.documentElement, "[test!='']:sizzle" );
} catch( pseudoError ) {
// 如果捕获到异常,说明伪类选择器工作正常
pseudoWorks = true;
}
// 定义一个Sizzle.matchesSelector方法用于检查节点是否匹配给定的选择器
Sizzle.matchesSelector = function( node, expr ) {
// 确保属性选择器被正确引用
expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']");
if ( !Sizzle.isXML( node ) ) {
try {
// 如果伪类选择器工作正常,或者表达式不包含伪类和不等于选择器
if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) {
var ret = matches.call( node, expr );
// 对于IE9断开的节点返回false或者检查节点是否在文档中而不是文档片段中
if ( ret || !disconnectedMatch || node.document && node.document.nodeType !== 11 ) {
return ret;
}
}
} catch(e) {}
}
3 years ago
4 weeks ago
// 如果上述方法失败使用Sizzle选择器进行匹配
return Sizzle(expr, null, null, [node]).length > 0;
};
3 years ago
}
4 weeks ago
})();
3 years ago
4 weeks ago
// 另一个自执行函数用于优化getElementsByClassName的使用
(function(){
var div = document.createElement("div");
3 years ago
4 weeks ago
// 创建一个包含两个div的测试元素其中一个有额外的类名'e'
div.innerHTML = "<div class='test e'></div><div class='test'></div>";
3 years ago
4 weeks ago
// 检查Opera是否不能找到第二个类名在9.6版本中)
// 同时确保getElementsByClassName方法确实存在
if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) {
return;
}
3 years ago
4 weeks ago
// 检查Safari是否缓存类属性不捕获变化在3.2版本中)
div.lastChild.className = "e";
3 years ago
4 weeks ago
// 如果修改后的类名只匹配到一个元素说明Safari的缓存问题存在
if ( div.getElementsByClassName("e").length === 1 ) {
return;
}
3 years ago
4 weeks ago
// 调整Sizzle选择器引擎的查找顺序优先使用CLASS查找
Expr.order.splice(1, 0, "CLASS");
// 定义一个CLASS查找方法如果浏览器支持getElementsByClassName则使用它
Expr.find.CLASS = function( match, context, isXML ) {
if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {
return context.getElementsByClassName(match[1]);
}
};
3 years ago
4 weeks ago
// 释放IE中的内存
div = null;
})();
3 years ago
4 weeks ago
// 定义一个方法用于在DOM树中按指定方向查找节点
function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
// 遍历checkSet数组中的每个元素
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
3 years ago
4 weeks ago
if ( elem ) {
var match = false;
3 years ago
4 weeks ago
// 根据dir方向获取下一个元素
elem = elem[dir];
3 years ago
4 weeks ago
// 遍历DOM树直到没有更多的元素
while ( elem ) {
// 如果元素已经被处理过(即已找到匹配的元素),则直接返回匹配的元素
if ( elem[ expando ] === doneName ) {
match = checkSet[elem.sizset];
break;
}
3 years ago
4 weeks ago
// 对于非XML文档标记当前元素为已处理
if ( elem.nodeType === 1 && !isXML ){
elem[ expando ] = doneName;
elem.sizset = i;
}
3 years ago
4 weeks ago
// 如果当前元素的节点名与cur匹配则找到匹配的元素
if ( elem.nodeName.toLowerCase() === cur ) {
match = elem;
break;
}
3 years ago
4 weeks ago
// 继续按dir方向查找下一个元素
elem = elem[dir];
3 years ago
}
4 weeks ago
// 更新checkSet中的当前元素为找到的匹配元素如果有的话
checkSet[i] = match;
3 years ago
}
}
}
4 weeks ago
// 定义一个函数dirCheck用于检查DOM树中的元素
function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
// 遍历checkSet数组中的每个元素
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
3 years ago
4 weeks ago
// 确保当前元素不是undefined或null
if ( elem ) {
var match = false;
3 years ago
4 weeks ago
// 根据dir参数通常是"parentNode"或"previousSibling")获取当前元素的相邻元素
elem = elem[dir];
3 years ago
4 weeks ago
// 遍历相邻元素
while ( elem ) {
// 检查元素是否已经被处理过通过expando属性
if ( elem[ expando ] === doneName ) {
// 如果已经处理过从checkSet中找到对应的元素
match = checkSet[elem.sizset];
break;
3 years ago
}
4 weeks ago
// 检查元素是否是元素节点
if ( elem.nodeType === 1 ) {
// 如果不是XML文档标记当前元素为已处理
if ( !isXML ) {
elem[ expando ] = doneName;
elem.sizset = i;
3 years ago
}
4 weeks ago
// 检查当前元素是否与cur匹配
if ( typeof cur !== "string" ) {
if ( elem === cur ) {
match = true;
break;
}
} else {
// 如果cur是字符串使用Sizzle.filter来检查是否匹配
if ( Sizzle.filter( cur, [elem] ).length > 0 ) {
match = elem;
break;
}
}
3 years ago
}
4 weeks ago
// 继续遍历相邻元素
elem = elem[dir];
3 years ago
}
4 weeks ago
// 更新checkSet中当前元素的值
checkSet[i] = match;
3 years ago
}
}
}
4 weeks ago
// 根据浏览器支持情况定义Sizzle.contains函数用于检查一个元素是否包含另一个元素
if ( document.documentElement.contains ) {
Sizzle.contains = function( a, b ) {
// 如果a和b不相等且a包含b则返回true
return a !== b && (a.contains ? a.contains(b) : true);
};
3 years ago
4 weeks ago
} else if ( document.documentElement.compareDocumentPosition ) {
Sizzle.contains = function( a, b ) {
// 使用compareDocumentPosition方法检查b是否在a中
return !!(a.compareDocumentPosition(b) & 16);
};
3 years ago
4 weeks ago
} else {
Sizzle.contains = function() {
// 如果浏览器不支持上述两种方法则总是返回false
return false;
};
3 years ago
}
4 weeks ago
// 定义一个函数Sizzle.isXML用于检查一个元素是否是XML文档的一部分
Sizzle.isXML = function( elem ) {
// 获取元素的ownerDocument的documentElement如果elem不存在则使用0
var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement;
3 years ago
4 weeks ago
// 如果documentElement存在且不是HTML节点则返回true
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
3 years ago
4 weeks ago
// 定义一个函数posProcess用于处理位置选择器
var posProcess = function( selector, context, seed ) {
var match,
tmpSet = [],
later = "",
root = context.nodeType ? [context] : context;
3 years ago
4 weeks ago
// 将选择器中的位置伪类提取出来
while ( (match = Expr.match.PSEUDO.exec( selector )) ) {
later += match[0];
selector = selector.replace( Expr.match.PSEUDO, "" );
}
3 years ago
4 weeks ago
// 如果选择器是相对选择器,则在其后添加"*"
selector = Expr.relative[selector] ? selector + "*" : selector;
3 years ago
4 weeks ago
// 遍历root中的每个元素使用Sizzle进行选择器匹配
for ( var i = 0, l = root.length; i < l; i++ ) {
Sizzle( selector, root[i], tmpSet, seed );
}
3 years ago
4 weeks ago
// 使用Sizzle.filter处理提取出来的位置伪类
return Sizzle.filter( later, tmpSet );
3 years ago
};
4 weeks ago
// EXPOSE将Sizzle的一些方法和属性暴露给jQuery
// 覆盖jQuery的attr方法
Sizzle.attr = jQuery.attr;
// 空的对象,用于存储属性映射
Sizzle.selectors.attrMap = {};
// 将jQuery的find方法替换为Sizzle
jQuery.find = Sizzle;
// 将Sizzle的选择器暴露给jQuery
jQuery.expr = Sizzle.selectors;
// 将Sizzle的过滤器暴露给jQuery
jQuery.expr[":"] = jQuery.expr.filters;
// 将Sizzle的唯一排序方法暴露给jQuery
jQuery.unique = Sizzle.uniqueSort;
// 将Sizzle的获取文本方法暴露给jQuery
jQuery.text = Sizzle.getText;
// 将Sizzle的isXML方法暴露给jQuery
jQuery.isXMLDoc = Sizzle.isXML;
// 将Sizzle的contains方法暴露给jQuery
jQuery.contains = Sizzle.contains;
// 立即执行函数表达式结束
})();
3 years ago
4 weeks ago
// 定义正则表达式匹配字符串末尾的"Until"
var runtil = /Until$/,
// 定义正则表达式匹配字符串开头的"parents"、"prevUntil"或"prevAll"
rparentsprev = /^(?:parents|prevUntil|prevAll)/,
// 定义正则表达式匹配逗号,用于分割多个选择器
rmultiselector = /,/,
// 定义正则表达式匹配简单选择器不包含ID、类名、属性或伪类选择器
isSimple = /^.[^:#\[\.,]*$/,
// 引用Array的slice方法
slice = Array.prototype.slice,
// 引用jQuery全局位置匹配的正则表达式
POS = jQuery.expr.match.globalPOS,
// 定义对象,其中的属性代表能确保返回唯一集合的方法
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
3 years ago
4 weeks ago
// 扩展jQuery的fn对象添加新的方法
jQuery.fn.extend({
// 在当前匹配的元素集合中查找后代元素
find: function( selector ) {
var self = this,
i, l;
// 如果selector不是字符串则将其视为jQuery对象并筛选出包含在当前集合中的元素
if ( typeof selector !== "string" ) {
return jQuery( selector ).filter(function() {
for ( i = 0, l = self.length; i < l; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
3 years ago
}
}
4 weeks ago
});
3 years ago
}
4 weeks ago
// 初始化结果集
var ret = this.pushStack( "", "find", selector ),
length, n, r;
3 years ago
4 weeks ago
// 遍历当前集合中的每个元素,查找符合条件的后代元素,并添加到结果集中
for ( i = 0, l = this.length; i < l; i++ ) {
length = ret.length;
jQuery.find( selector, this[i], ret );
// 如果不是第一个元素,则确保结果集中的元素是唯一的
if ( i > 0 ) {
for ( n = length; n < ret.length; n++ ) {
for ( r = 0; r < length; r++ ) {
if ( ret[r] === ret[n] ) {
ret.splice(n--, 1);
break;
}
}
}
3 years ago
}
}
4 weeks ago
return ret;
},
3 years ago
4 weeks ago
// 检查当前集合中的元素是否包含指定的目标元素
has: function( target ) {
var targets = jQuery( target );
return this.filter(function() {
for ( var i = 0, l = targets.length; i < l; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
3 years ago
4 weeks ago
// 从当前集合中筛选出符合选择器的元素
not: function( selector ) {
return this.pushStack( winnow(this, selector, false), "not", selector);
},
3 years ago
4 weeks ago
// 从当前集合中筛选出符合选择器的元素与not相反
filter: function( selector ) {
return this.pushStack( winnow(this, selector, true), "filter", selector );
},
3 years ago
4 weeks ago
// 检查当前集合中的元素是否匹配选择器
is: function( selector ) {
return !!selector && (
typeof selector === "string" ?
// 如果这是位置选择器,检查当前元素是否在返回集合中
// 以确保如$("p:first").is("p:last")在只有两个"p"的文档中不会返回true
POS.test( selector ) ?
jQuery( selector, this.context ).index( this[0] ) >= 0 :
// 否则,检查当前集合中是否有元素匹配选择器
jQuery.filter( selector, this ).length > 0 :
// 如果selector不是字符串则将其视为jQuery对象并检查当前集合中是否有元素匹配
this.filter( selector ).length > 0 );
},
3 years ago
4 weeks ago
// 从当前元素开始向上遍历DOM树查找符合选择器的最接近的祖先元素
closest: function( selectors, context ) {
var ret = [], i, l, cur = this[0];
// 如果selectors是数组自jQuery 1.7起已弃用)
if ( jQuery.isArray( selectors ) ) {
var level = 1;
// 向上遍历DOM树直到cur为空、没有父节点或到达context
while ( cur && cur.ownerDocument && cur !== context ) {
for ( i = 0; i < selectors.length; i++ ) {
// 如果当前元素匹配选择器
if ( jQuery( cur ).is( selectors[ i ] ) ) {
// 将选择器、匹配的元素和层级添加到结果集中
ret.push({ selector: selectors[ i ], elem: cur, level: level });
}
3 years ago
}
4 weeks ago
// 继续向上遍历DOM树
cur = cur.parentNode;
level++;
3 years ago
}
4 weeks ago
return ret;
3 years ago
}
4 weeks ago
// 定义一个名为closest的方法用于查找当前jQuery对象中每个元素的最接近的祖先元素该祖先元素匹配给定的选择器
var pos = POS.test( selectors ) || typeof selectors !== "string" ?
// 如果选择器是一个正则表达式匹配的对象或者不是字符串类型则使用jQuery查找元素
3 years ago
jQuery( selectors, context || this.context ) :
4 weeks ago
// 否则将pos设置为0表示不使用位置测试
3 years ago
0;
4 weeks ago
// 遍历当前jQuery对象中的每个元素
for ( i = 0, l = this.length; i < l; i++ ) {
cur = this[i];
// 在当前元素的祖先链中向上遍历
while ( cur ) {
// 如果使用位置测试,则检查当前元素是否在位置集合中
// 否则,检查当前元素是否匹配给定的选择器
if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
// 如果找到匹配的元素,将其添加到结果集中,并跳出循环
ret.push( cur );
3 years ago
break;
4 weeks ago
} else {
// 如果没有找到匹配的元素,继续向上遍历至父节点
cur = cur.parentNode;
// 如果到达文档的根节点、脱离文档的元素节点、文档片段节点或上下文节点,则停止遍历
if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) {
break;
}
3 years ago
}
}
}
4 weeks ago
// 如果结果集中包含多个元素,则去重
ret = ret.length > 1 ? jQuery.unique( ret ) : ret;
3 years ago
4 weeks ago
// 将结果集作为新的jQuery对象返回并设置其前一个对象链
return this.pushStack( ret, "closest", selectors );
},
3 years ago
4 weeks ago
// 定义一个名为index的方法用于确定元素在匹配集中的位置
index: function( elem ) {
3 years ago
4 weeks ago
// 如果没有参数,则返回当前元素在其父节点中的索引位置
if ( !elem ) {
return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1;
}
3 years ago
4 weeks ago
// 如果参数是字符串,则将其视为选择器,并返回当前元素在匹配该选择器的元素集中的索引位置
if ( typeof elem === "string" ) {
return jQuery.inArray( this[0], jQuery( elem ) );
}
3 years ago
4 weeks ago
// 否则返回参数元素在当前jQuery对象中的索引位置
return jQuery.inArray(
// 如果参数是jQuery对象则使用其第一个元素
elem.jquery ? elem[0] : elem, this );
},
3 years ago
4 weeks ago
// 定义一个名为add的方法用于将元素添加到当前jQuery对象中
add: function( selector, context ) {
// 根据参数类型创建一个新的jQuery对象或元素数组
var set = typeof selector === "string" ?
jQuery( selector, context ) :
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
// 合并当前jQuery对象和新的jQuery对象或元素数组
all = jQuery.merge( this.get(), set );
// 如果合并后的元素集中有脱离文档的元素,则直接返回;否则,去重后返回
return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ?
all :
jQuery.unique( all ) );
},
3 years ago
4 weeks ago
// 定义一个名为andSelf的方法用于将当前jQuery对象的前一个对象添加到当前对象中
andSelf: function() {
return this.add( this.prevObject );
}
});
3 years ago
4 weeks ago
// 定义一个函数,用于检查一个元素是否脱离了文档
function isDisconnected( node ) {
// 如果节点不存在、没有父节点、或者父节点是文档片段节点则返回true
return !node || !node.parentNode || node.parentNode.nodeType === 11;
3 years ago
}
4 weeks ago
// 为jQuery对象定义一系列遍历DOM树的方法如parent、parents等
jQuery.each({
parent: function( elem ) {
// 返回元素的父节点如果父节点是文档片段节点则返回null
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
// 省略其他方法的详细注释,以保持简洁...
// ...
// 这些方法主要通过遍历DOM树来查找元素如父节点、祖先节点、兄弟节点等
// ...
contents: function( elem ) {
// 如果元素是iframe则返回其内容文档或内容窗口的文档否则返回元素的子节点数组
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.makeArray( elem.childNodes );
3 years ago
}
4 weeks ago
}, function( name, fn ) {
// 为jQuery对象定义每个遍历方法这些方法可以接收可选的选择器参数来过滤结果
jQuery.fn[ name ] = function( until, selector ) {
// 使用map方法遍历当前jQuery对象中的每个元素并应用给定的函数
var ret = jQuery.map( this, fn, until );
3 years ago
4 weeks ago
// 如果方法名不包含"Until",则将第二个参数视为选择器
if ( !runtil.test( name ) ) {
selector = until;
}
3 years ago
4 weeks ago
// 如果提供了选择器参数并且它是一个字符串则使用filter方法过滤结果
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
3 years ago
4 weeks ago
// 如果结果集中包含多个元素,并且该方法不是保证唯一性的,则去重
ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
3 years ago
4 weeks ago
// 如果当前jQuery对象包含多个元素或者选择器是多选择器并且方法名是以prev开头的则反转结果集
if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
3 years ago
4 weeks ago
// 将结果集作为新的jQuery对象返回并设置其前一个对象链和方法名等信息
return this.pushStack( ret, name, slice.call( arguments ).join(",") );
};
});
3 years ago
4 weeks ago
// 扩展jQuery对象添加一些自定义的方法
jQuery.extend({
// 过滤元素集合,根据选择器表达式,可选地排除匹配的元素
filter: function( expr, elems, not ) {
// 如果设置了not参数将表达式修改为:not(原表达式)
if ( not ) {
expr = ":not(" + expr + ")";
}
// 如果elems只有一个元素则直接检查该元素是否匹配选择器
// 匹配则返回该元素的数组,不匹配则返回空数组
// 否则使用jQuery.find.matches来查找匹配的元素
return elems.length === 1 ?
jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
jQuery.find.matches(expr, elems);
},
3 years ago
4 weeks ago
// 根据给定的方向父节点或子节点和直到哪个节点停止遍历DOM树
dir: function( elem, dir, until ) {
var matched = [],
// 存储匹配元素的数组
cur = elem[ dir ];
// 从当前元素的指定方向开始
// 遍历DOM树直到达到条件
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
// 如果是元素节点,则添加到匹配数组中
matched.push( cur );
}
cur = cur[dir];
// 继续遍历
3 years ago
}
4 weeks ago
return matched;
// 返回匹配元素的数组
},
3 years ago
4 weeks ago
// 根据给定的结果索引和方向从当前元素开始查找第n个兄弟元素
nth: function( cur, result, dir, elem ) {
result = result || 1;
// 默认结果为1
var num = 0;
// 计数器
3 years ago
4 weeks ago
// 遍历兄弟元素直到找到第result个元素
for ( ; cur; cur = cur[dir] ) {
if ( cur.nodeType === 1 && ++num === result ) {
break;
}
3 years ago
}
4 weeks ago
return cur;
// 返回找到的元素
},
3 years ago
4 weeks ago
// 获取当前元素的所有兄弟元素(不包括自己),根据给定的起始节点
sibling: function( n, elem ) {
var r = [];
// 存储兄弟元素的数组
3 years ago
4 weeks ago
// 遍历所有兄弟元素
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
// 如果是元素节点且不是当前元素,则添加到数组中
r.push( n );
}
3 years ago
}
4 weeks ago
return r;
// 返回兄弟元素的数组
}
});
3 years ago
4 weeks ago
// 实现filter和not的相同功能根据给定的元素集合、条件函数和保留/排除标志来筛选元素
function winnow( elements, qualifier, keep ) {
3 years ago
4 weeks ago
// 确保qualifier不是null或undefined否则Firefox 4的indexOf会报错
// 设置为0以跳过字符串检查
qualifier = qualifier || 0;
3 years ago
4 weeks ago
// 如果qualifier是一个函数则对每个元素执行该函数并根据返回值和keep标志筛选元素
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep(elements, function( elem, i ) {
var retVal = !!qualifier.call( elem, i, elem );
return retVal === keep;
});
3 years ago
4 weeks ago
// 如果qualifier是一个DOM节点则筛选与qualifier相同的元素
} else if ( qualifier.nodeType ) {
return jQuery.grep(elements, function( elem, i ) {
return ( elem === qualifier ) === keep;
});
3 years ago
4 weeks ago
// 如果qualifier是一个字符串则首先筛选出所有元素节点
// 然后根据字符串是简单选择器还是复杂选择器来进一步筛选
} else if ( typeof qualifier === "string" ) {
var filtered = jQuery.grep(elements, function( elem ) {
return elem.nodeType === 1;
});
3 years ago
4 weeks ago
if ( isSimple.test( qualifier ) ) {
// 如果是简单选择器
return jQuery.filter(qualifier, filtered, !keep);
} else {
// 如果是复杂选择器
qualifier = jQuery.filter( qualifier, filtered );
}
3 years ago
}
4 weeks ago
// 使用jQuery.grep和inArray来筛选元素根据元素是否在qualifier数组中以及keep标志
return jQuery.grep(elements, function( elem, i ) {
return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep;
});
}
3 years ago
4 weeks ago
// 创建一个安全的文档片段用于插入DOM元素
// 这个方法通过创建一系列的元素来避免某些浏览器的安全限制
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
// 获取需要创建的元素名称列表
safeFrag = document.createDocumentFragment();
// 创建一个文档片段
// 如果文档片段支持createElement方法
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
// 对列表中的每个元素名称,创建一个元素并添加到文档片段中
list.pop()
);
}
}
return safeFrag;
// 返回安全的文档片段
}
3 years ago
4 weeks ago
// 定义一组特定的HTML标签名这些标签名将被用于后续的正则表达式匹配
var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
// 匹配jQuery版本号例如 jQuery123456789="123456" 或 jQuery123456789="null"
rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g,
// 匹配字符串开头的空白字符
rleadingWhitespace = /^\s+/,
// 匹配自闭合的HTML标签但排除了area, br, col, embed, hr, img, input, link, meta, param这些标签
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,
// 匹配HTML标签名
rtagName = /<([\w:]+)/,
// 匹配<tbody>标签
rtbody = /<tbody/i,
// 匹配HTML标签或HTML实体
rhtml = /<|&#?\w+;/,
// 匹配<script>或<style>标签
rnoInnerhtml = /<(?:script|style)/i,
// 匹配可能不需要缓存处理的标签,如<script>, <object>, <embed>, <option>, <style>
rnocache = /<(?:script|object|embed|option|style)/i,
// 匹配不需要shim缓存处理的特定标签
rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
// 匹配checked属性无论是否带有值
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
// 匹配JavaScript或ECMAScript脚本标签
rscriptType = /\/(java|ecma)script/i,
// 匹配注释或CDATA段的开始
rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)/,
// 定义元素包装映射,用于将某些元素包裹在特定的父元素中
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
area: [ 1, "<map>", "</map>" ],
_default: [ 0, "", "" ]
},
// 创建一个安全的文档片段用于操作DOM
safeFragment = createSafeFragment( document );
3 years ago
4 weeks ago
// 为一些特殊标签设置相同的包装规则
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
3 years ago
4 weeks ago
// 如果浏览器不支持HTML序列化则使用div作为默认包装元素
if ( !jQuery.support.htmlSerialize ) {
wrapMap._default = [ 1, "div<div>", "</div>" ];
3 years ago
}
4 weeks ago
// 扩展jQuery的fn对象添加一些新的方法
jQuery.fn.extend({
// 设置或获取匹配元素的文本内容
4 weeks ago
text: function (value) {
return jQuery.access(this, function (value) {
4 weeks ago
return value === undefined ?
4 weeks ago
jQuery.text(this) :
this.empty().append((this[0] && this[0].ownerDocument || document).createTextNode(value));
}, null, value, arguments.length);
4 weeks ago
},
3 years ago
4 weeks ago
// 将所有匹配元素包裹在一个HTML结构中
4 weeks ago
wrapAll: function (html) {
if (jQuery.isFunction(html)) {
return this.each(function (i) {
jQuery(this).wrapAll(html.call(this, i));
4 weeks ago
});
}
3 years ago
4 weeks ago
if (this[0]) {
4 weeks ago
// 克隆html结构并插入到DOM中
4 weeks ago
var wrap = jQuery(html, this[0].ownerDocument).eq(0).clone(true);
3 years ago
4 weeks ago
if (this[0].parentNode) {
wrap.insertBefore(this[0]);
4 weeks ago
}
3 years ago
4 weeks ago
// 将匹配元素插入到克隆的html结构中
4 weeks ago
wrap.map(function () {
4 weeks ago
var elem = this;
3 years ago
4 weeks ago
while (elem.firstChild && elem.firstChild.nodeType === 1) {
4 weeks ago
elem = elem.firstChild;
}
3 years ago
4 weeks ago
return elem;
4 weeks ago
}).append(this);
3 years ago
}
4 weeks ago
return this;
},
3 years ago
4 weeks ago
// 将匹配元素的内部内容包裹在一个HTML结构中
4 weeks ago
wrapInner: function (html) {
if (jQuery.isFunction(html)) {
return this.each(function (i) {
jQuery(this).wrapInner(html.call(this, i));
4 weeks ago
});
}
3 years ago
4 weeks ago
return this.each(function () {
var self = jQuery(this),
4 weeks ago
contents = self.contents();
3 years ago
4 weeks ago
if (contents.length) {
4 weeks ago
// 如果元素有子节点则将子节点包裹在html结构中
4 weeks ago
contents.wrapAll(html);
3 years ago
4 weeks ago
} else {
// 如果没有子节点则直接追加html
4 weeks ago
self.append(html);
4 weeks ago
}
3 years ago
});
4 weeks ago
},
3 years ago
4 weeks ago
// 将每个匹配元素包裹在一个HTML结构中
4 weeks ago
wrap: function (html) {
var isFunction = jQuery.isFunction(html);
3 years ago
4 weeks ago
return this.each(function (i) {
4 weeks ago
// 对每个元素执行包装操作如果html是函数则传入当前元素的索引并调用函数
4 weeks ago
jQuery(this).wrapAll(isFunction ? html.call(this, i) : html);
4 weeks ago
});
},
3 years ago
4 weeks ago
// 移除匹配元素的父元素,但保留元素本身及其子元素
4 weeks ago
unwrap: function () {
return this.parent().each(function () {
if (!jQuery.nodeName(this, "body")) {
4 weeks ago
// 如果不是body元素则用其子节点替换该元素
4 weeks ago
jQuery(this).replaceWith(this.childNodes);
4 weeks ago
}
}).end();
},
3 years ago
4 weeks ago
// 在匹配元素的末尾追加内容
4 weeks ago
append: function () {
return this.domManip(arguments, true, function (elem) {
if (this.nodeType === 1) {
this.appendChild(elem);
4 weeks ago
}
});
},
3 years ago
4 weeks ago
// 在匹配元素的前面追加内容
4 weeks ago
prepend: function () {
return this.domManip(arguments, true, function (elem) {
if (this.nodeType === 1) {
this.insertBefore(elem, this.firstChild);
4 weeks ago
}
});
},
3 years ago
4 weeks ago
// before方法在当前元素之前插入内容
before: function () {
// 如果当前jQuery对象至少有一个元素并且这个元素有父节点
if (this[0] && this[0].parentNode) {
// 使用domManip方法插入内容位置在当前元素之前
return this.domManip(arguments, false, function (elem) {
this.parentNode.insertBefore(elem, this);
});
} else if (arguments.length) { // 如果有参数传入
// 清理参数将它们转换成一个jQuery对象数组
var set = jQuery.clean(arguments);
// 将当前jQuery对象中的元素添加到set数组末尾
set.push.apply(set, this.toArray());
// 返回一个新的jQuery对象包含set数组中的元素
return this.pushStack(set, "before", arguments);
}
},
3 years ago
4 weeks ago
// after方法在当前元素之后插入内容
after: function () {
// 如果当前jQuery对象至少有一个元素并且这个元素有父节点
if (this[0] && this[0].parentNode) {
// 使用domManip方法插入内容位置在当前元素的下一个兄弟节点之前即当前元素之后
return this.domManip(arguments, false, function (elem) {
this.parentNode.insertBefore(elem, this.nextSibling);
});
} else if (arguments.length) { // 如果有参数传入
// 创建一个新的jQuery对象包含当前元素
var set = this.pushStack(this, "after", arguments);
// 清理参数并将它们添加到set中
set.push.apply(set, jQuery.clean(arguments));
// 返回set
return set;
}
},
3 years ago
4 weeks ago
// remove方法移除当前元素
remove: function (selector, keepData) {
// 遍历当前jQuery对象中的每个元素
for (var i = 0, elem; (elem = this[i]) != null; i++) {
// 如果没有指定选择器或者当前元素匹配选择器
if (!selector || jQuery.filter(selector, [elem]).length) {
// 如果没有指定keepData并且元素是DOM元素
if (!keepData && elem.nodeType === 1) {
// 清理元素及其所有子元素上的数据
jQuery.cleanData(elem.getElementsByTagName("*"));
jQuery.cleanData([elem]);
}
3 years ago
4 weeks ago
// 如果元素有父节点,则从父节点中移除该元素
if (elem.parentNode) {
elem.parentNode.removeChild(elem);
}
3 years ago
}
}
4 weeks ago
// 返回当前jQuery对象
return this;
},
3 years ago
4 weeks ago
// empty方法移除当前元素的所有子元素
empty: function () {
// 遍历当前jQuery对象中的每个元素
for (var i = 0, elem; (elem = this[i]) != null; i++) {
// 如果元素是DOM元素
if (elem.nodeType === 1) {
// 清理元素上的所有子元素的数据
jQuery.cleanData(elem.getElementsByTagName("*"));
}
3 years ago
4 weeks ago
// 移除元素的所有子节点
while (elem.firstChild) {
elem.removeChild(elem.firstChild);
}
3 years ago
}
4 weeks ago
// 返回当前jQuery对象
return this;
},
3 years ago
4 weeks ago
// clone方法克隆当前元素
clone: function (dataAndEvents, deepDataAndEvents) {
// 设置dataAndEvents和deepDataAndEvents的默认值
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
3 years ago
4 weeks ago
// 返回一个新的jQuery对象包含当前元素的克隆
return this.map(function () {
return jQuery.clone(this, dataAndEvents, deepDataAndEvents);
});
},
3 years ago
4 weeks ago
// html方法获取或设置当前元素的HTML内容
html: function (value) {
// 使用jQuery.access方法根据是否传入value值来获取或设置HTML内容
return jQuery.access(this, function (value) {
var elem = this[0] || {},
// 获取第一个元素,如果不存在则为空对象
i = 0,
l = this.length;
// 当前jQuery对象的长度
// 如果没有传入value值则获取HTML内容
if (value === undefined) {
return elem.nodeType === 1 ?
// 如果元素是DOM元素
elem.innerHTML.replace(rinlinejQuery, "") :
// 移除jQuery特有的标记
null;
}
3 years ago
4 weeks ago
// 如果value是字符串并且满足特定条件不触发innerHTML的bug
if (typeof value === "string" && !rnoInnerhtml.test(value) &&
(jQuery.support.leadingWhitespace || !rleadingWhitespace.test(value)) &&
!wrapMap[(rtagName.exec(value) || ["", ""])[1].toLowerCase()]) {
3 years ago
4 weeks ago
// 尝试直接设置innerHTML
value = value.replace(rxhtmlTag, "<$1></$2>");
3 years ago
4 weeks ago
try {
for (; i < l; i++) {
elem = this[i] || {};
// 获取当前元素
if (elem.nodeType === 1) {
// 如果元素是DOM元素
jQuery.cleanData(elem.getElementsByTagName("*"));
// 清理数据
elem.innerHTML = value;
// 设置innerHTML
}
}
3 years ago
4 weeks ago
elem = 0;
// 重置elem
3 years ago
4 weeks ago
// 如果使用innerHTML失败则使用备用方法
} catch (e) {
3 years ago
}
4 weeks ago
}
3 years ago
4 weeks ago
// 如果value值存在则清空当前元素的内容并追加value值
if (elem) {
this.empty().append(value);
}
}, null, value, arguments.length);
},
3 years ago
4 weeks ago
// 定义一个 replaceWith 方法,用于替换当前匹配的元素集合
replaceWith: function (value) {
// 确保至少有一个元素且该元素有父节点
if (this[0] && this[0].parentNode) {
// 如果传入的值是一个函数,则对每个匹配的元素执行此函数,并替换元素
if (jQuery.isFunction(value)) {
return this.each(function (i) {
var self = jQuery(this), old = self.html();
// 获取当前元素并保存其HTML内容
self.replaceWith(value.call(this, i, old));
// 调用函数并替换当前元素
});
}
3 years ago
4 weeks ago
// 如果传入的值不是字符串则将其转换为jQuery对象并从DOM中分离
if (typeof value !== "string") {
value = jQuery(value).detach();
}
// 对每个匹配的元素执行替换操作
return this.each(function () {
var next = this.nextSibling,
// 获取当前元素的下一个兄弟节点
parent = this.parentNode;
// 获取当前元素的父节点
jQuery(this).remove();
// 从DOM中移除当前元素
// 如果存在下一个兄弟节点,则在其之前插入新元素
if (next) {
jQuery(next).before(value);
} else {
// 否则,将新元素追加到父节点的末尾
jQuery(parent).append(value);
}
});
} else {
// 如果没有匹配的元素或元素没有父节点,则根据传入值的不同进行处理
return this.length ?
this.pushStack(jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value) : // 如果传入值是一个函数则执行它并返回结果否则直接返回jQuery对象
this; // 如果没有匹配的元素则直接返回当前jQuery对象
3 years ago
}
4 weeks ago
},
// 定义一个 detach 方法用于从DOM中分离元素
detach: function (selector) {
return this.remove(selector, true);
// 调用 remove 方法并设置第二个参数为 true 以实现分离而非删除
},
3 years ago
4 weeks ago
// 定义一个 domManip 方法用于在DOM中进行复杂的操作如插入、删除、替换等
domManip: function (args, table, callback) {
var results, first, fragment, parent,
value = args[0],
// 获取传入的操作值
scripts = [];
// 用于存储脚本元素的数组
// 如果不支持复选框的克隆,并且传入的值是字符串且包含复选框,则对每个元素单独处理
if (!jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test(value)) {
return this.each(function () {
jQuery(this).domManip(args, table, callback, true);
// 递归调用并设置额外的参数
3 years ago
});
}
4 weeks ago
// 如果传入的值是一个函数则对每个匹配的元素执行此函数并传入参数进行DOM操作
if (jQuery.isFunction(value)) {
return this.each(function (i) {
var self = jQuery(this);
args[0] = value.call(this, i, table ? self.html() : undefined);
// 调用函数并更新传入值
self.domManip(args, table, callback); // 递归调用 domManip 方法
});
3 years ago
}
4 weeks ago
// 确保有至少一个匹配的元素
if (this[0]) {
parent = value && value.parentNode;
// 获取传入值的父节点
3 years ago
4 weeks ago
// 如果传入的值是一个文档片段且其子节点数量与当前匹配的元素数量相同,则直接使用该片段
if (jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length) {
results = {fragment: parent}; // 设置结果对象,包含文档片段
3 years ago
} else {
4 weeks ago
// 否则,根据传入的值和当前匹配的元素创建一个新的文档片段
results = jQuery.buildFragment(args, this, scripts);
3 years ago
}
4 weeks ago
fragment = results.fragment; // 获取文档片段
3 years ago
4 weeks ago
// 如果文档片段只有一个子节点,则直接使用该子节点
if (fragment.childNodes.length === 1) {
first = fragment = fragment.firstChild;
} else {
// 否则,使用文档片段的第一个子节点
first = fragment.firstChild;
}
3 years ago
4 weeks ago
if (first) {
table = table && jQuery.nodeName(first, "tr");
// 检查第一个子节点是否为表格行
// 对每个匹配的元素执行回调函数,传入处理后的文档片段或子节点
for (var i = 0, l = this.length, lastIndex = l - 1; i < l; i++) {
callback.call(
table ?
root(this[i], first) :
// 如果是表格行,则使用特殊方法处理
this[i],
// 根据情况使用克隆的文档片段或原始片段的最后一个元素
results.cacheable || (l > 1 && i < lastIndex) ?
jQuery.clone(fragment, true, true) :
fragment
);
}
}
3 years ago
4 weeks ago
// 如果 scripts 数组的长度不为0即存在脚本元素
if (scripts.length) {
// 使用 jQuery 的 each 方法遍历 scripts 数组
jQuery.each(scripts, function (i, elem) {
// 如果当前脚本元素有 src 属性,即外部脚本
if (elem.src) {
// 使用 jQuery 的 ajax 方法异步(但这里设置为 false即同步加载外部脚本
jQuery.ajax({
type: "GET", // 请求类型
global: false,
// 不触发全局 AJAX 事件处理程序
url: elem.src,
// 请求的 URL
async: false,
// 强制同步请求
dataType: "script"
// 预期服务器返回的数据类型
});
} else {
// 如果脚本是内联的,则直接执行
jQuery.globalEval((elem.text || elem.textContent || elem.innerHTML || "").replace(rcleanScript, "/*$0*/"));
// 注意rcleanScript 未在代码段中定义,可能是用于清理脚本内容的正则表达式
}
3 years ago
4 weeks ago
// 如果脚本元素有父节点,则从 DOM 中移除该脚本元素
if (elem.parentNode) {
elem.parentNode.removeChild(elem);
}
});
3 years ago
}
}
4 weeks ago
// 返回当前 jQuery 对象,支持链式调用
return this;
3 years ago
}
4 weeks ago
});
3 years ago
4 weeks ago
// 定义一个函数,用于处理表格元素,确保操作的是 tbody 元素或为其添加一个
function root( elem, cur ) {
return jQuery.nodeName(elem, "table") ?
(elem.getElementsByTagName("tbody")[0] ||
// 如果表格有 tbody则返回第一个
elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
// 否则,为表格添加一个新的 tbody 并返回
elem;
// 如果不是表格,则直接返回元素本身
}
3 years ago
4 weeks ago
// 定义一个函数,用于克隆元素时复制事件和数据
function cloneCopyEvent( src, dest ) {
3 years ago
4 weeks ago
// 如果目标元素不是 DOM 元素或源元素没有数据,则直接返回
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
3 years ago
4 weeks ago
var type, i, l,
oldData = jQuery._data( src ),
// 获取源元素的数据
curData = jQuery._data( dest, oldData ),
// 在目标元素上设置与源元素相同的数据引用
events = oldData.events;
// 获取源元素的事件
if ( events ) {
delete curData.handle;
// 删除目标元素上的 handle 引用
curData.events = {};
// 为目标元素创建一个新的事件对象
// 遍历源元素的所有事件类型
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
// 将事件添加到目标元素
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
3 years ago
4 weeks ago
// 如果目标元素有数据,则复制这些数据
if ( curData.data ) {
curData.data = jQuery.extend( {}, curData.data );
}
3 years ago
}
4 weeks ago
// 定义一个函数,用于在克隆元素时修复属性
function cloneFixAttributes( src, dest ) {
var nodeName;
3 years ago
4 weeks ago
// 如果目标元素不是 DOM 元素,则直接返回
if ( dest.nodeType !== 1 ) {
return;
}
3 years ago
4 weeks ago
// 使用 clearAttributes 清除目标元素的属性(如果存在此方法)
// 注意:这也会清除事件,但我们稍后会重新添加
if ( dest.clearAttributes ) {
dest.clearAttributes();
}
3 years ago
4 weeks ago
// 使用 mergeAttributes 合并源元素的属性到目标元素(如果存在此方法)
if ( dest.mergeAttributes ) {
dest.mergeAttributes( src );
}
3 years ago
4 weeks ago
// 获取目标元素的节点名称(小写)
nodeName = dest.nodeName.toLowerCase();
3 years ago
4 weeks ago
// 对于 object 元素,使用 outerHTML 来确保正确克隆
if ( nodeName === "object" ) {
dest.outerHTML = src.outerHTML;
3 years ago
4 weeks ago
// 对于 checkbox 和 radio确保复制 checked 状态和值
} else if ( nodeName === "input" && (src.type === "checkbox" || src.type === "radio") ) {
if ( src.checked ) {
dest.defaultChecked = dest.checked = src.checked;
}
if ( dest.value !== src.value ) {
dest.value = src.value;
}
3 years ago
4 weeks ago
// 对于 option 元素,确保复制 selected 状态
} else if ( nodeName === "option" ) {
dest.selected = src.defaultSelected;
3 years ago
4 weeks ago
// 对于 input 和 textarea 元素,确保复制 defaultValue
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
3 years ago
4 weeks ago
// 对于 script 元素,确保复制文本内容
} else if ( nodeName === "script" && dest.text !== src.text ) {
dest.text = src.text;
}
3 years ago
// Event data gets referenced instead of copied if the expando
// gets copied too
dest.removeAttribute( jQuery.expando );
// Clear flags for bubbling special change/submit events, they must
// be reattached when the newly cloned events are first activated
dest.removeAttribute( "_submit_attached" );
dest.removeAttribute( "_change_attached" );
}
jQuery.buildFragment = function( args, nodes, scripts ) {
var fragment, cacheable, cacheresults, doc,
first = args[ 0 ];
// nodes may contain either an explicit document object,
// a jQuery collection or context object.
// If nodes[0] contains a valid object to assign to doc
if ( nodes && nodes[0] ) {
doc = nodes[0].ownerDocument || nodes[0];
}
// Ensure that an attr object doesn't incorrectly stand in as a document object
// Chrome and Firefox seem to allow this to occur and will throw exception
// Fixes #8950
if ( !doc.createDocumentFragment ) {
doc = document;
}
// Only cache "small" (1/2 KB) HTML strings that are associated with the main document
// Cloning options loses the selected state, so don't cache them
// IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
// Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
// Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501
if ( args.length === 1 && typeof first === "string" && first.length < 512 && doc === document &&
first.charAt(0) === "<" && !rnocache.test( first ) &&
(jQuery.support.checkClone || !rchecked.test( first )) &&
(jQuery.support.html5Clone || !rnoshimcache.test( first )) ) {
cacheable = true;
cacheresults = jQuery.fragments[ first ];
if ( cacheresults && cacheresults !== 1 ) {
fragment = cacheresults;
}
}
if ( !fragment ) {
fragment = doc.createDocumentFragment();
jQuery.clean( args, doc, fragment, scripts );
}
if ( cacheable ) {
jQuery.fragments[ first ] = cacheresults ? fragment : 1;
}
return { fragment: fragment, cacheable: cacheable };
};
jQuery.fragments = {};
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var ret = [],
insert = jQuery( selector ),
parent = this.length === 1 && this[0].parentNode;
if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
insert[ original ]( this[0] );
return this;
} else {
for ( var i = 0, l = insert.length; i < l; i++ ) {
var elems = ( i > 0 ? this.clone(true) : this ).get();
jQuery( insert[i] )[ original ]( elems );
ret = ret.concat( elems );
}
return this.pushStack( ret, name, insert.selector );
}
};
});
function getAll( elem ) {
if ( typeof elem.getElementsByTagName !== "undefined" ) {
return elem.getElementsByTagName( "*" );
} else if ( typeof elem.querySelectorAll !== "undefined" ) {
return elem.querySelectorAll( "*" );
} else {
return [];
}
}
// Used in clean, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( elem.type === "checkbox" || elem.type === "radio" ) {
elem.defaultChecked = elem.checked;
}
}
// Finds all inputs and passes them to fixDefaultChecked
function findInputs( elem ) {
var nodeName = ( elem.nodeName || "" ).toLowerCase();
if ( nodeName === "input" ) {
fixDefaultChecked( elem );
// Skip scripts, get other children
} else if ( nodeName !== "script" && typeof elem.getElementsByTagName !== "undefined" ) {
jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked );
}
}
// Derived From: http://www.iecss.com/shimprove/javascript/shimprove.1-0-1.js
function shimCloneNode( elem ) {
var div = document.createElement( "div" );
safeFragment.appendChild( div );
div.innerHTML = elem.outerHTML;
return div.firstChild;
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var srcElements,
destElements,
i,
// IE<=8 does not properly clone detached, unknown element nodes
clone = jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ?
elem.cloneNode( true ) :
shimCloneNode( elem );
if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// IE copies events bound via attachEvent when using cloneNode.
// Calling detachEvent on the clone will also remove the events
// from the original. In order to get around this, we use some
// proprietary methods to clear the events. Thanks to MooTools
// guys for this hotness.
cloneFixAttributes( elem, clone );
// Using Sizzle here is crazy slow, so we use getElementsByTagName instead
srcElements = getAll( elem );
destElements = getAll( clone );
// Weird iteration because IE will replace the length property
// with an element if you are cloning the body and one of the
// elements on the page has a name or id of "length"
for ( i = 0; srcElements[i]; ++i ) {
// Ensure that the destination node is not null; Fixes #9587
if ( destElements[i] ) {
cloneFixAttributes( srcElements[i], destElements[i] );
}
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
cloneCopyEvent( elem, clone );
if ( deepDataAndEvents ) {
srcElements = getAll( elem );
destElements = getAll( clone );
for ( i = 0; srcElements[i]; ++i ) {
cloneCopyEvent( srcElements[i], destElements[i] );
}
}
}
srcElements = destElements = null;
// Return the cloned set
return clone;
},
clean: function( elems, context, fragment, scripts ) {
var checkScriptType, script, j,
ret = [];
context = context || document;
// !context.createElement fails in IE with an error but returns typeof 'object'
if ( typeof context.createElement === "undefined" ) {
context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
}
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
if ( typeof elem === "number" ) {
elem += "";
}
if ( !elem ) {
continue;
}
// Convert html string into DOM nodes
if ( typeof elem === "string" ) {
if ( !rhtml.test( elem ) ) {
elem = context.createTextNode( elem );
} else {
// Fix "XHTML"-style tags in all browsers
elem = elem.replace(rxhtmlTag, "<$1></$2>");
// Trim whitespace, otherwise indexOf won't work as expected
var tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(),
wrap = wrapMap[ tag ] || wrapMap._default,
depth = wrap[0],
div = context.createElement("div"),
safeChildNodes = safeFragment.childNodes,
remove;
// Append wrapper element to unknown element safe doc fragment
if ( context === document ) {
// Use the fragment we've already created for this document
safeFragment.appendChild( div );
} else {
// Use a fragment created with the owner document
createSafeFragment( context ).appendChild( div );
}
// Go to html and back, then peel off extra wrappers
div.innerHTML = wrap[1] + elem + wrap[2];
// Move to the right depth
while ( depth-- ) {
div = div.lastChild;
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !jQuery.support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
var hasBody = rtbody.test(elem),
tbody = tag === "table" && !hasBody ?
div.firstChild && div.firstChild.childNodes :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !hasBody ?
div.childNodes :
[];
for ( j = tbody.length - 1; j >= 0 ; --j ) {
if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
tbody[ j ].parentNode.removeChild( tbody[ j ] );
}
}
}
// IE completely kills leading whitespace when innerHTML is used
if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
}
elem = div.childNodes;
// Clear elements from DocumentFragment (safeFragment or otherwise)
// to avoid hoarding elements. Fixes #11356
if ( div ) {
div.parentNode.removeChild( div );
// Guard against -1 index exceptions in FF3.6
if ( safeChildNodes.length > 0 ) {
remove = safeChildNodes[ safeChildNodes.length - 1 ];
if ( remove && remove.parentNode ) {
remove.parentNode.removeChild( remove );
}
}
}
}
}
// Resets defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
var len;
if ( !jQuery.support.appendChecked ) {
if ( elem[0] && typeof (len = elem.length) === "number" ) {
for ( j = 0; j < len; j++ ) {
findInputs( elem[j] );
}
} else {
findInputs( elem );
}
}
if ( elem.nodeType ) {
ret.push( elem );
} else {
ret = jQuery.merge( ret, elem );
}
}
if ( fragment ) {
checkScriptType = function( elem ) {
return !elem.type || rscriptType.test( elem.type );
};
for ( i = 0; ret[i]; i++ ) {
script = ret[i];
if ( scripts && jQuery.nodeName( script, "script" ) && (!script.type || rscriptType.test( script.type )) ) {
scripts.push( script.parentNode ? script.parentNode.removeChild( script ) : script );
} else {
if ( script.nodeType === 1 ) {
var jsTags = jQuery.grep( script.getElementsByTagName( "script" ), checkScriptType );
ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) );
}
fragment.appendChild( script );
}
}
}
return ret;
},
cleanData: function( elems ) {
var data, id,
cache = jQuery.cache,
special = jQuery.event.special,
deleteExpando = jQuery.support.deleteExpando;
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) {
continue;
}
id = elem[ jQuery.expando ];
if ( id ) {
data = cache[ id ];
if ( data && data.events ) {
for ( var type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
// Null the DOM reference to avoid IE6/7/8 leak (#7054)
if ( data.handle ) {
data.handle.elem = null;
}
}
if ( deleteExpando ) {
delete elem[ jQuery.expando ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( jQuery.expando );
}
delete cache[ id ];
}
}
}
});
var ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity=([^)]*)/,
// fixed for IE9, see #8346
rupper = /([A-Z]|^ms)/g,
rnum = /^[\-+]?(?:\d*\.)?\d+$/i,
rnumnonpx = /^-?(?:\d*\.)?\d+(?!px)[^\d\s]+$/i,
rrelNum = /^([\-+])=([\-+.\de]+)/,
rmargin = /^margin/,
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
// order is important!
cssExpand = [ "Top", "Right", "Bottom", "Left" ],
curCSS,
getComputedStyle,
currentStyle;
jQuery.fn.css = function( name, value ) {
return jQuery.access( this, function( elem, name, value ) {
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
};
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
} else {
return elem.style.opacity;
}
}
}
},
// Exclude the following css properties to add px
cssNumber: {
"fillOpacity": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, origName = jQuery.camelCase( name ),
style = elem.style, hooks = jQuery.cssHooks[ origName ];
name = jQuery.cssProps[ origName ] || origName;
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( +( ret[1] + 1) * +ret[2] ) + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that NaN and null values aren't set. See: #7116
if ( value == null || type === "number" && isNaN( value ) ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value )) !== undefined ) {
// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
// Fixes bug #5509
try {
style[ name ] = value;
} catch(e) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra ) {
var ret, hooks;
// Make sure that we're working with the right name
name = jQuery.camelCase( name );
hooks = jQuery.cssHooks[ name ];
name = jQuery.cssProps[ name ] || name;
// cssFloat needs a special treatment
if ( name === "cssFloat" ) {
name = "float";
}
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) {
return ret;
// Otherwise, if a way to get the computed value exists, use that
} else if ( curCSS ) {
return curCSS( elem, name );
}
},
// A method for quickly swapping in/out CSS properties to get correct calculations
swap: function( elem, options, callback ) {
var old = {},
ret, name;
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.call( elem );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
}
});
// DEPRECATED in 1.3, Use jQuery.css() instead
jQuery.curCSS = jQuery.css;
if ( document.defaultView && document.defaultView.getComputedStyle ) {
getComputedStyle = function( elem, name ) {
var ret, defaultView, computedStyle, width,
style = elem.style;
name = name.replace( rupper, "-$1" ).toLowerCase();
if ( (defaultView = elem.ownerDocument.defaultView) &&
(computedStyle = defaultView.getComputedStyle( elem, null )) ) {
ret = computedStyle.getPropertyValue( name );
if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) {
ret = jQuery.style( elem, name );
}
}
// A tribute to the "awesome hack by Dean Edwards"
// WebKit uses "computed value (percentage if specified)" instead of "used value" for margins
// which is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( !jQuery.support.pixelMargin && computedStyle && rmargin.test( name ) && rnumnonpx.test( ret ) ) {
width = style.width;
style.width = ret;
ret = computedStyle.width;
style.width = width;
}
return ret;
};
}
if ( document.documentElement.currentStyle ) {
currentStyle = function( elem, name ) {
var left, rsLeft, uncomputed,
ret = elem.currentStyle && elem.currentStyle[ name ],
style = elem.style;
// Avoid setting ret to empty string here
// so we don't default to auto
if ( ret == null && style && (uncomputed = style[ name ]) ) {
ret = uncomputed;
}
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
if ( rnumnonpx.test( ret ) ) {
// Remember the original values
left = style.left;
rsLeft = elem.runtimeStyle && elem.runtimeStyle.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
elem.runtimeStyle.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : ret;
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
elem.runtimeStyle.left = rsLeft;
}
}
return ret === "" ? "auto" : ret;
};
}
curCSS = getComputedStyle || currentStyle;
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property
var val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
i = name === "width" ? 1 : 0,
len = 4;
if ( val > 0 ) {
if ( extra !== "border" ) {
for ( ; i < len; i += 2 ) {
if ( !extra ) {
val -= parseFloat( jQuery.css( elem, "padding" + cssExpand[ i ] ) ) || 0;
}
if ( extra === "margin" ) {
val += parseFloat( jQuery.css( elem, extra + cssExpand[ i ] ) ) || 0;
} else {
val -= parseFloat( jQuery.css( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0;
}
}
}
return val + "px";
}
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test(val) ) {
return val;
}
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
// Add padding, border, margin
if ( extra ) {
for ( ; i < len; i += 2 ) {
val += parseFloat( jQuery.css( elem, "padding" + cssExpand[ i ] ) ) || 0;
if ( extra !== "padding" ) {
val += parseFloat( jQuery.css( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0;
}
if ( extra === "margin" ) {
val += parseFloat( jQuery.css( elem, extra + cssExpand[ i ]) ) || 0;
}
}
}
return val + "px";
}
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
if ( elem.offsetWidth !== 0 ) {
return getWidthOrHeight( elem, name, extra );
} else {
return jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
});
}
}
},
set: function( elem, value ) {
return rnum.test( value ) ?
value + "px" :
value;
}
};
});
if ( !jQuery.support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
( parseFloat( RegExp.$1 ) / 100 ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle,
opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
filter = currentStyle && currentStyle.filter || style.filter || "";
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" ) {
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute( "filter" );
// if there there is no filter style applied in a css rule, we are done
if ( currentStyle && !currentStyle.filter ) {
return;
}
}
// otherwise, set new filter values
style.filter = ralpha.test( filter ) ?
filter.replace( ralpha, opacity ) :
filter + " " + opacity;
}
};
}
jQuery(function() {
// This hook cannot be added until DOM ready because the support test
// for it is not run until after DOM ready
if ( !jQuery.support.reliableMarginRight ) {
jQuery.cssHooks.marginRight = {
get: function( elem, computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap( elem, { "display": "inline-block" }, function() {
if ( computed ) {
return curCSS( elem, "margin-right" );
} else {
return elem.style.marginRight;
}
});
}
};
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.hidden = function( elem ) {
var width = elem.offsetWidth,
height = elem.offsetHeight;
return ( width === 0 && height === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
}
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i,
// assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [ value ],
expanded = {};
for ( i = 0; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
});
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rhash = /#.*$/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rquery = /\?/,
rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
rselectTextarea = /^(?:select|textarea)/i,
rspacesAjax = /\s+/,
rts = /([?&])_=[^&]*/,
rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,
// Keep a copy of the old load method
_load = jQuery.fn.load,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Document location
ajaxLocation,
// Document location segments
ajaxLocParts,
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = ["*/"] + ["*"];
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
if ( jQuery.isFunction( func ) ) {
var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ),
i = 0,
length = dataTypes.length,
dataType,
list,
placeBefore;
// For each dataType in the dataTypeExpression
for ( ; i < length; i++ ) {
dataType = dataTypes[ i ];
// We control if we're asked to add before
// any existing element
placeBefore = /^\+/.test( dataType );
if ( placeBefore ) {
dataType = dataType.substr( 1 ) || "*";
}
list = structure[ dataType ] = structure[ dataType ] || [];
// then we add to the structure accordingly
list[ placeBefore ? "unshift" : "push" ]( func );
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR,
dataType /* internal */, inspected /* internal */ ) {
dataType = dataType || options.dataTypes[ 0 ];
inspected = inspected || {};
inspected[ dataType ] = true;
var list = structure[ dataType ],
i = 0,
length = list ? list.length : 0,
executeOnly = ( structure === prefilters ),
selection;
for ( ; i < length && ( executeOnly || !selection ); i++ ) {
selection = list[ i ]( options, originalOptions, jqXHR );
// If we got redirected to another dataType
// we try there if executing only and not done already
if ( typeof selection === "string" ) {
if ( !executeOnly || inspected[ selection ] ) {
selection = undefined;
} else {
options.dataTypes.unshift( selection );
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, selection, inspected );
}
}
}
// If we're only executing or nothing was selected
// we try the catchall dataType if not done already
if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) {
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, "*", inspected );
}
// unnecessary when only executing (prefilters)
// but it'll be ignored by the caller in that case
return selection;
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var key, deep,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
}
jQuery.fn.extend({
load: function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
// Don't do a request if no elements are being requested
} else if ( !this.length ) {
return this;
}
var off = url.indexOf( " " );
if ( off >= 0 ) {
var selector = url.slice( off, url.length );
url = url.slice( 0, off );
}
// Default to a GET request
var type = "GET";
// If the second parameter was provided
if ( params ) {
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( typeof params === "object" ) {
params = jQuery.param( params, jQuery.ajaxSettings.traditional );
type = "POST";
}
}
var self = this;
// Request the remote document
jQuery.ajax({
url: url,
type: type,
dataType: "html",
data: params,
// Complete callback (responseText is used internally)
complete: function( jqXHR, status, responseText ) {
// Store the response as specified by the jqXHR object
responseText = jqXHR.responseText;
// If successful, inject the HTML into all the matched elements
if ( jqXHR.isResolved() ) {
// #4825: Get the actual response in case
// a dataFilter is present in ajaxSettings
jqXHR.done(function( r ) {
responseText = r;
});
// See if a selector was specified
self.html( selector ?
// Create a dummy div to hold the results
jQuery("<div>")
// inject the contents of the document in, removing the scripts
// to avoid any 'Permission Denied' errors in IE
.append(responseText.replace(rscript, ""))
// Locate the specified elements
.find(selector) :
// If not, just inject the full result
responseText );
}
if ( callback ) {
self.each( callback, [ responseText, status, jqXHR ] );
}
}
});
return this;
},
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function(){
return this.elements ? jQuery.makeArray( this.elements ) : this;
})
.filter(function(){
return this.name && !this.disabled &&
( this.checked || rselectTextarea.test( this.nodeName ) ||
rinput.test( this.type ) );
})
.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val, i ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
// Attach a bunch of functions for handling common AJAX events
jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){
jQuery.fn[ o ] = function( f ){
return this.on( o, f );
};
});
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
type: method,
url: url,
data: data,
success: callback,
dataType: type
});
};
});
jQuery.extend({
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
if ( settings ) {
// Building a settings object
ajaxExtend( target, jQuery.ajaxSettings );
} else {
// Extending ajaxSettings
settings = target;
target = jQuery.ajaxSettings;
}
ajaxExtend( target, settings );
return target;
},
ajaxSettings: {
url: ajaxLocation,
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
type: "GET",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
processData: true,
async: true,
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
traditional: false,
headers: {},
*/
accepts: {
xml: "application/xml, text/xml",
html: "text/html",
text: "text/plain",
json: "application/json, text/javascript",
"*": allTypes
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText"
},
// List of data converters
// 1) key format is "source_type destination_type" (a single space in-between)
// 2) the catchall symbol "*" can be used for source_type
converters: {
// Convert anything to text
"* text": window.String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
context: true,
url: true
}
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var // Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events
// It's the callbackContext if one was provided in the options
// and if it's a DOM node or a jQuery collection
globalEventContext = callbackContext !== s &&
( callbackContext.nodeType || callbackContext instanceof jQuery ) ?
jQuery( callbackContext ) : jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks( "once memory" ),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// ifModified key
ifModifiedKey,
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// Response headers
responseHeadersString,
responseHeaders,
// transport
transport,
// timeout handle
timeoutTimer,
// Cross-domain detection vars
parts,
// The jqXHR state
state = 0,
// To know if global events are to be dispatched
fireGlobals,
// Loop variable
i,
// Fake xhr
jqXHR = {
readyState: 0,
// Caches the header
setRequestHeader: function( name, value ) {
if ( !state ) {
var lname = name.toLowerCase();
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while( ( match = rheaders.exec( responseHeadersString ) ) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match === undefined ? null : match;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Cancel the request
abort: function( statusText ) {
statusText = statusText || "abort";
if ( transport ) {
transport.abort( statusText );
}
done( 0, statusText );
return this;
}
};
// Callback for when everything is done
// It is defined here because jslint complains if it is declared
// at the end of the function (which would be more logical and readable)
function done( status, nativeStatusText, responses, headers ) {
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
var isSuccess,
success,
error,
statusText = nativeStatusText,
response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined,
lastModified,
etag;
// If successful, handle type chaining
if ( status >= 200 && status < 300 || status === 304 ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) {
jQuery.lastModified[ ifModifiedKey ] = lastModified;
}
if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) {
jQuery.etag[ ifModifiedKey ] = etag;
}
}
// If not modified
if ( status === 304 ) {
statusText = "notmodified";
isSuccess = true;
// If we have data
} else {
try {
success = ajaxConvert( s, response );
statusText = "success";
isSuccess = true;
} catch(e) {
// We have a parsererror
statusText = "parsererror";
error = e;
}
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if ( !statusText || status ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = "" + ( nativeStatusText || statusText );
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger( "ajaxStop" );
}
}
}
// Attach deferreds
deferred.promise( jqXHR );
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
jqXHR.complete = completeDeferred.add;
// Status-dependent callbacks
jqXHR.statusCode = function( map ) {
if ( map ) {
var tmp;
if ( state < 2 ) {
for ( tmp in map ) {
statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
}
} else {
tmp = map[ jqXHR.status ];
jqXHR.then( tmp, tmp );
}
}
return this;
};
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// We also use the url parameter if available
s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax );
// Determine if a cross-domain request is in order
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] != ajaxLocParts[ 1 ] || parts[ 2 ] != ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
);
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefilter, stop there
if ( state === 2 ) {
return false;
}
// We can fire global events as of now if asked to
fireGlobals = s.global;
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger( "ajaxStart" );
}
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Get ifModifiedKey before adding the anti-cache parameter
ifModifiedKey = s.url;
// Add anti-cache in url if needed
if ( s.cache === false ) {
var ts = jQuery.now(),
// try replacing _= if it is there
ret = s.url.replace( rts, "$1_=" + ts );
// if nothing was replaced, add timestamp to the end
s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
ifModifiedKey = ifModifiedKey || s.url;
if ( jQuery.lastModified[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] );
}
if ( jQuery.etag[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] );
}
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
// Abort if not done already
jqXHR.abort();
return false;
}
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout( function(){
jqXHR.abort( "timeout" );
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch (e) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
return jqXHR;
},
// Serialize an array of form elements or a set of
// key/values into a query string
param: function( a, traditional ) {
var s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : value;
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( var prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
}
});
function buildParams( prefix, obj, traditional, add ) {
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// If array item is non-scalar (array or object), encode its
// numeric index to resolve deserialization ambiguity issues.
// Note that rack (as of 1.0.0) can't currently deserialize
// nested arrays properly, and attempting to do so may cause
// a server error. Possible fixes are to modify rack's
// deserialization algorithm or to provide an option or flag
// to force array serialization to be shallow.
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( var name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
// This is still on the jQuery object... for now
// Want to move this to jQuery.ajax some day
jQuery.extend({
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {}
});
/* Handles responses to an ajax request:
* - sets all responseXXX fields accordingly
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var contents = s.contents,
dataTypes = s.dataTypes,
responseFields = s.responseFields,
ct,
type,
finalDataType,
firstDataType;
// Fill responseXXX fields
for ( type in responseFields ) {
if ( type in responses ) {
jqXHR[ responseFields[type] ] = responses[ type ];
}
}
// Remove auto dataType and get content-type in the process
while( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader( "content-type" );
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
// Chain conversions given the request and the original response
function ajaxConvert( s, response ) {
// Apply the dataFilter if provided
if ( s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
var dataTypes = s.dataTypes,
converters = {},
i,
key,
length = dataTypes.length,
tmp,
// Current and previous dataTypes
current = dataTypes[ 0 ],
prev,
// Conversion expression
conversion,
// Conversion function
conv,
// Conversion functions (transitive conversion)
conv1,
conv2;
// For each dataType in the chain
for ( i = 1; i < length; i++ ) {
// Create converters map
// with lowercased keys
if ( i === 1 ) {
for ( key in s.converters ) {
if ( typeof key === "string" ) {
converters[ key.toLowerCase() ] = s.converters[ key ];
}
}
}
// Get the dataTypes
prev = current;
current = dataTypes[ i ];
// If current is auto dataType, update it to prev
if ( current === "*" ) {
current = prev;
// If no auto and dataTypes are actually different
} else if ( prev !== "*" && prev !== current ) {
// Get the converter
conversion = prev + " " + current;
conv = converters[ conversion ] || converters[ "* " + current ];
// If there is no direct converter, search transitively
if ( !conv ) {
conv2 = undefined;
for ( conv1 in converters ) {
tmp = conv1.split( " " );
if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) {
conv2 = converters[ tmp[1] + " " + current ];
if ( conv2 ) {
conv1 = converters[ conv1 ];
if ( conv1 === true ) {
conv = conv2;
} else if ( conv2 === true ) {
conv = conv1;
}
break;
}
}
}
}
// If we found no converter, dispatch an error
if ( !( conv || conv2 ) ) {
jQuery.error( "No conversion from " + conversion.replace(" "," to ") );
}
// If found converter is not an equivalence
if ( conv !== true ) {
// Convert with 1 or 2 converters accordingly
response = conv ? conv( response ) : conv2( conv1(response) );
}
}
}
return response;
}
var jsc = jQuery.now(),
jsre = /(\=)\?(&|$)|\?\?/i;
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
return jQuery.expando + "_" + ( jsc++ );
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var inspectData = ( typeof s.data === "string" ) && /^application\/x\-www\-form\-urlencoded/.test( s.contentType );
if ( s.dataTypes[ 0 ] === "jsonp" ||
s.jsonp !== false && ( jsre.test( s.url ) ||
inspectData && jsre.test( s.data ) ) ) {
var responseContainer,
jsonpCallback = s.jsonpCallback =
jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback,
previous = window[ jsonpCallback ],
url = s.url,
data = s.data,
replace = "$1" + jsonpCallback + "$2";
if ( s.jsonp !== false ) {
url = url.replace( jsre, replace );
if ( s.url === url ) {
if ( inspectData ) {
data = data.replace( jsre, replace );
}
if ( s.data === data ) {
// Add callback manually
url += (/\?/.test( url ) ? "&" : "?") + s.jsonp + "=" + jsonpCallback;
}
}
}
s.url = url;
s.data = data;
// Install callback
window[ jsonpCallback ] = function( response ) {
responseContainer = [ response ];
};
// Clean-up function
jqXHR.always(function() {
// Set callback back to previous value
window[ jsonpCallback ] = previous;
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( previous ) ) {
window[ jsonpCallback ]( responseContainer[ 0 ] );
}
});
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( !responseContainer ) {
jQuery.error( jsonpCallback + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Delegate to script
return "script";
}
});
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /javascript|ecmascript/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
s.global = false;
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script,
head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement( "script" );
script.async = "async";
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( head && script.parentNode ) {
head.removeChild( script );
}
// Dereference the script
script = undefined;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709 and #4378).
head.insertBefore( script, head.firstChild );
},
abort: function() {
if ( script ) {
script.onload( 0, 1 );
}
}
};
}
});
var // #5280: Internet Explorer will keep connections alive if we don't abort on unload
xhrOnUnloadAbort = window.ActiveXObject ? function() {
// Abort all pending requests
for ( var key in xhrCallbacks ) {
xhrCallbacks[ key ]( 0, 1 );
}
} : false,
xhrId = 0,
xhrCallbacks;
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch( e ) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject( "Microsoft.XMLHTTP" );
} catch( e ) {}
}
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject ?
/* Microsoft failed to properly
* implement the XMLHttpRequest in IE7 (can't request local files),
* so we use the ActiveXObject when it is available
* Additionally XMLHttpRequest can be disabled in IE7/IE8 so
* we need a fallback.
*/
function() {
return !this.isLocal && createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
// Determine support properties
(function( xhr ) {
jQuery.extend( jQuery.support, {
ajax: !!xhr,
cors: !!xhr && ( "withCredentials" in xhr )
});
})( jQuery.ajaxSettings.xhr() );
// Create transport if the browser can provide an xhr
if ( jQuery.support.ajax ) {
jQuery.ajaxTransport(function( s ) {
// Cross domain only allowed if supported through XMLHttpRequest
if ( !s.crossDomain || jQuery.support.cors ) {
var callback;
return {
send: function( headers, complete ) {
// Get a new xhr
var xhr = s.xhr(),
handle,
i;
// Open the socket
// Passing null username, generates a login popup on Opera (#2865)
if ( s.username ) {
xhr.open( s.type, s.url, s.async, s.username, s.password );
} else {
xhr.open( s.type, s.url, s.async );
}
// Apply custom fields if provided
if ( s.xhrFields ) {
for ( i in s.xhrFields ) {
xhr[ i ] = s.xhrFields[ i ];
}
}
// Override mime type if needed
if ( s.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( s.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !s.crossDomain && !headers["X-Requested-With"] ) {
headers[ "X-Requested-With" ] = "XMLHttpRequest";
}
// Need an extra try/catch for cross domain requests in Firefox 3
try {
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
} catch( _ ) {}
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( s.hasContent && s.data ) || null );
// Listener
callback = function( _, isAbort ) {
var status,
statusText,
responseHeaders,
responses,
xml;
// Firefox throws exceptions when accessing properties
// of an xhr when a network error occured
// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
try {
// Was never called and is aborted or complete
if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Only called once
callback = undefined;
// Do not keep as active anymore
if ( handle ) {
xhr.onreadystatechange = jQuery.noop;
if ( xhrOnUnloadAbort ) {
delete xhrCallbacks[ handle ];
}
}
// If it's an abort
if ( isAbort ) {
// Abort it manually if needed
if ( xhr.readyState !== 4 ) {
xhr.abort();
}
} else {
status = xhr.status;
responseHeaders = xhr.getAllResponseHeaders();
responses = {};
xml = xhr.responseXML;
// Construct response list
if ( xml && xml.documentElement /* #4958 */ ) {
responses.xml = xml;
}
// When requesting binary data, IE6-9 will throw an exception
// on any attempt to access responseText (#11426)
try {
responses.text = xhr.responseText;
} catch( _ ) {
}
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch( e ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && s.isLocal && !s.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
} catch( firefoxAccessException ) {
if ( !isAbort ) {
complete( -1, firefoxAccessException );
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, responseHeaders );
}
};
// if we're in sync mode or it's in cache
// and has been retrieved directly (IE6 & IE7)
// we need to manually fire the callback
if ( !s.async || xhr.readyState === 4 ) {
callback();
} else {
handle = ++xhrId;
if ( xhrOnUnloadAbort ) {
// Create the active xhrs callbacks list if needed
// and attach the unload handler
if ( !xhrCallbacks ) {
xhrCallbacks = {};
jQuery( window ).unload( xhrOnUnloadAbort );
}
// Add to list of active xhrs callbacks
xhrCallbacks[ handle ] = callback;
}
xhr.onreadystatechange = callback;
}
},
abort: function() {
if ( callback ) {
callback(0,1);
}
}
};
}
});
}
var elemdisplay = {},
iframe, iframeDoc,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,
timerId,
fxAttrs = [
// height animations
[ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ],
// width animations
[ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ],
// opacity animations
[ "opacity" ]
],
fxNow;
jQuery.fn.extend({
show: function( speed, easing, callback ) {
var elem, display;
if ( speed || speed === 0 ) {
return this.animate( genFx("show", 3), speed, easing, callback );
} else {
for ( var i = 0, j = this.length; i < j; i++ ) {
elem = this[ i ];
if ( elem.style ) {
display = elem.style.display;
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !jQuery._data(elem, "olddisplay") && display === "none" ) {
display = elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( (display === "" && jQuery.css(elem, "display") === "none") ||
!jQuery.contains( elem.ownerDocument.documentElement, elem ) ) {
jQuery._data( elem, "olddisplay", defaultDisplay(elem.nodeName) );
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( i = 0; i < j; i++ ) {
elem = this[ i ];
if ( elem.style ) {
display = elem.style.display;
if ( display === "" || display === "none" ) {
elem.style.display = jQuery._data( elem, "olddisplay" ) || "";
}
}
}
return this;
}
},
hide: function( speed, easing, callback ) {
if ( speed || speed === 0 ) {
return this.animate( genFx("hide", 3), speed, easing, callback);
} else {
var elem, display,
i = 0,
j = this.length;
for ( ; i < j; i++ ) {
elem = this[i];
if ( elem.style ) {
display = jQuery.css( elem, "display" );
if ( display !== "none" && !jQuery._data( elem, "olddisplay" ) ) {
jQuery._data( elem, "olddisplay", display );
}
}
}
// Set the display of the elements in a second loop
// to avoid the constant reflow
for ( i = 0; i < j; i++ ) {
if ( this[i].style ) {
this[i].style.display = "none";
}
}
return this;
}
},
// Save the old toggle function
_toggle: jQuery.fn.toggle,
toggle: function( fn, fn2, callback ) {
var bool = typeof fn === "boolean";
if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) {
this._toggle.apply( this, arguments );
} else if ( fn == null || bool ) {
this.each(function() {
var state = bool ? fn : jQuery(this).is(":hidden");
jQuery(this)[ state ? "show" : "hide" ]();
});
} else {
this.animate(genFx("toggle", 3), fn, fn2, callback);
}
return this;
},
fadeTo: function( speed, to, easing, callback ) {
return this.filter(":hidden").css("opacity", 0).show().end()
.animate({opacity: to}, speed, easing, callback);
},
animate: function( prop, speed, easing, callback ) {
var optall = jQuery.speed( speed, easing, callback );
if ( jQuery.isEmptyObject( prop ) ) {
return this.each( optall.complete, [ false ] );
}
// Do not change referenced properties as per-property easing will be lost
prop = jQuery.extend( {}, prop );
function doAnimation() {
// XXX 'this' does not always have a nodeName when running the
// test suite
if ( optall.queue === false ) {
jQuery._mark( this );
}
var opt = jQuery.extend( {}, optall ),
isElement = this.nodeType === 1,
hidden = isElement && jQuery(this).is(":hidden"),
name, val, p, e, hooks, replace,
parts, start, end, unit,
method;
// will store per property easing and be used to determine when an animation is complete
opt.animatedProperties = {};
// first pass over propertys to expand / normalize
for ( p in prop ) {
name = jQuery.camelCase( p );
if ( p !== name ) {
prop[ name ] = prop[ p ];
delete prop[ p ];
}
if ( ( hooks = jQuery.cssHooks[ name ] ) && "expand" in hooks ) {
replace = hooks.expand( prop[ name ] );
delete prop[ name ];
// not quite $.extend, this wont overwrite keys already present.
// also - reusing 'p' from above because we have the correct "name"
for ( p in replace ) {
if ( ! ( p in prop ) ) {
prop[ p ] = replace[ p ];
}
}
}
}
for ( name in prop ) {
val = prop[ name ];
// easing resolution: per property > opt.specialEasing > opt.easing > 'swing' (default)
if ( jQuery.isArray( val ) ) {
opt.animatedProperties[ name ] = val[ 1 ];
val = prop[ name ] = val[ 0 ];
} else {
opt.animatedProperties[ name ] = opt.specialEasing && opt.specialEasing[ name ] || opt.easing || 'swing';
}
if ( val === "hide" && hidden || val === "show" && !hidden ) {
return opt.complete.call( this );
}
if ( isElement && ( name === "height" || name === "width" ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
if ( jQuery.css( this, "display" ) === "inline" &&
jQuery.css( this, "float" ) === "none" ) {
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( !jQuery.support.inlineBlockNeedsLayout || defaultDisplay( this.nodeName ) === "inline" ) {
this.style.display = "inline-block";
} else {
this.style.zoom = 1;
}
}
}
}
if ( opt.overflow != null ) {
this.style.overflow = "hidden";
}
for ( p in prop ) {
e = new jQuery.fx( this, opt, p );
val = prop[ p ];
if ( rfxtypes.test( val ) ) {
// Tracks whether to show or hide based on private
// data attached to the element
method = jQuery._data( this, "toggle" + p ) || ( val === "toggle" ? hidden ? "show" : "hide" : 0 );
if ( method ) {
jQuery._data( this, "toggle" + p, method === "show" ? "hide" : "show" );
e[ method ]();
} else {
e[ val ]();
}
} else {
parts = rfxnum.exec( val );
start = e.cur();
if ( parts ) {
end = parseFloat( parts[2] );
unit = parts[3] || ( jQuery.cssNumber[ p ] ? "" : "px" );
// We need to compute starting value
if ( unit !== "px" ) {
jQuery.style( this, p, (end || 1) + unit);
start = ( (end || 1) / e.cur() ) * start;
jQuery.style( this, p, start + unit);
}
// If a +=/-= token was provided, we're doing a relative animation
if ( parts[1] ) {
end = ( (parts[ 1 ] === "-=" ? -1 : 1) * end ) + start;
}
e.custom( start, end, unit );
} else {
e.custom( start, val, "" );
}
}
}
// For JS strict compliance
return true;
}
return optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each(function() {
var index,
hadTimers = false,
timers = jQuery.timers,
data = jQuery._data( this );
// clear marker counters if we know they won't be
if ( !gotoEnd ) {
jQuery._unmark( true, this );
}
function stopQueue( elem, data, index ) {
var hooks = data[ index ];
jQuery.removeData( elem, index, true );
hooks.stop( gotoEnd );
}
if ( type == null ) {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && index.indexOf(".run") === index.length - 4 ) {
stopQueue( this, data, index );
}
}
} else if ( data[ index = type + ".run" ] && data[ index ].stop ){
stopQueue( this, data, index );
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
if ( gotoEnd ) {
// force the next step to be the last
timers[ index ]( true );
} else {
timers[ index ].saveState();
}
hadTimers = true;
timers.splice( index, 1 );
}
}
// start the next in the queue if the last step wasn't forced
// timers currently will call their complete callbacks, which will dequeue
// but only if they were gotoEnd
if ( !( gotoEnd && hadTimers ) ) {
jQuery.dequeue( this, type );
}
});
}
});
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout( clearFxNow, 0 );
return ( fxNow = jQuery.now() );
}
function clearFxNow() {
fxNow = undefined;
}
// Generate parameters to create a standard animation
function genFx( type, num ) {
var obj = {};
jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice( 0, num )), function() {
obj[ this ] = type;
});
return obj;
}
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx( "show", 1 ),
slideUp: genFx( "hide", 1 ),
slideToggle: genFx( "toggle", 1 ),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
});
jQuery.extend({
speed: function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
// normalize opt.queue - true/undefined/null -> "fx"
if ( opt.queue == null || opt.queue === true ) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function( noUnmark ) {
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue ) {
jQuery.dequeue( this, opt.queue );
} else if ( noUnmark !== false ) {
jQuery._unmark( this );
}
};
return opt;
},
easing: {
linear: function( p ) {
return p;
},
swing: function( p ) {
return ( -Math.cos( p*Math.PI ) / 2 ) + 0.5;
}
},
timers: [],
fx: function( elem, options, prop ) {
this.options = options;
this.elem = elem;
this.prop = prop;
options.orig = options.orig || {};
}
});
jQuery.fx.prototype = {
// Simple function for setting a style value
update: function() {
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
( jQuery.fx.step[ this.prop ] || jQuery.fx.step._default )( this );
},
// Get the current size
cur: function() {
if ( this.elem[ this.prop ] != null && (!this.elem.style || this.elem.style[ this.prop ] == null) ) {
return this.elem[ this.prop ];
}
var parsed,
r = jQuery.css( this.elem, this.prop );
// Empty strings, null, undefined and "auto" are converted to 0,
// complex values such as "rotate(1rad)" are returned as is,
// simple values such as "10px" are parsed to Float.
return isNaN( parsed = parseFloat( r ) ) ? !r || r === "auto" ? 0 : r : parsed;
},
// Start an animation from one number to another
custom: function( from, to, unit ) {
var self = this,
fx = jQuery.fx;
this.startTime = fxNow || createFxNow();
this.end = to;
this.now = this.start = from;
this.pos = this.state = 0;
this.unit = unit || this.unit || ( jQuery.cssNumber[ this.prop ] ? "" : "px" );
function t( gotoEnd ) {
return self.step( gotoEnd );
}
t.queue = this.options.queue;
t.elem = this.elem;
t.saveState = function() {
if ( jQuery._data( self.elem, "fxshow" + self.prop ) === undefined ) {
if ( self.options.hide ) {
jQuery._data( self.elem, "fxshow" + self.prop, self.start );
} else if ( self.options.show ) {
jQuery._data( self.elem, "fxshow" + self.prop, self.end );
}
}
};
if ( t() && jQuery.timers.push(t) && !timerId ) {
timerId = setInterval( fx.tick, fx.interval );
}
},
// Simple 'show' function
show: function() {
var dataShow = jQuery._data( this.elem, "fxshow" + this.prop );
// Remember where we started, so that we can go back to it later
this.options.orig[ this.prop ] = dataShow || jQuery.style( this.elem, this.prop );
this.options.show = true;
// Begin the animation
// Make sure that we start at a small width/height to avoid any flash of content
if ( dataShow !== undefined ) {
// This show is picking up where a previous hide or show left off
this.custom( this.cur(), dataShow );
} else {
this.custom( this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur() );
}
// Start by showing the element
jQuery( this.elem ).show();
},
// Simple 'hide' function
hide: function() {
// Remember where we started, so that we can go back to it later
this.options.orig[ this.prop ] = jQuery._data( this.elem, "fxshow" + this.prop ) || jQuery.style( this.elem, this.prop );
this.options.hide = true;
// Begin the animation
this.custom( this.cur(), 0 );
},
// Each step of an animation
step: function( gotoEnd ) {
var p, n, complete,
t = fxNow || createFxNow(),
done = true,
elem = this.elem,
options = this.options;
if ( gotoEnd || t >= options.duration + this.startTime ) {
this.now = this.end;
this.pos = this.state = 1;
this.update();
options.animatedProperties[ this.prop ] = true;
for ( p in options.animatedProperties ) {
if ( options.animatedProperties[ p ] !== true ) {
done = false;
}
}
if ( done ) {
// Reset the overflow
if ( options.overflow != null && !jQuery.support.shrinkWrapBlocks ) {
jQuery.each( [ "", "X", "Y" ], function( index, value ) {
elem.style[ "overflow" + value ] = options.overflow[ index ];
});
}
// Hide the element if the "hide" operation was done
if ( options.hide ) {
jQuery( elem ).hide();
}
// Reset the properties, if the item has been hidden or shown
if ( options.hide || options.show ) {
for ( p in options.animatedProperties ) {
jQuery.style( elem, p, options.orig[ p ] );
jQuery.removeData( elem, "fxshow" + p, true );
// Toggle data is no longer needed
jQuery.removeData( elem, "toggle" + p, true );
}
}
// Execute the complete function
// in the event that the complete function throws an exception
// we must ensure it won't be called twice. #5684
complete = options.complete;
if ( complete ) {
options.complete = false;
complete.call( elem );
}
}
return false;
} else {
// classical easing cannot be used with an Infinity duration
if ( options.duration == Infinity ) {
this.now = t;
} else {
n = t - this.startTime;
this.state = n / options.duration;
// Perform the easing function, defaults to swing
this.pos = jQuery.easing[ options.animatedProperties[this.prop] ]( this.state, n, 0, 1, options.duration );
this.now = this.start + ( (this.end - this.start) * this.pos );
}
// Perform the next step of the animation
this.update();
}
return true;
}
};
jQuery.extend( jQuery.fx, {
tick: function() {
var timer,
timers = jQuery.timers,
i = 0;
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Checks the timer has not already been removed
if ( !timer() && timers[ i ] === timer ) {
timers.splice( i--, 1 );
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
},
interval: 13,
stop: function() {
clearInterval( timerId );
timerId = null;
},
speeds: {
slow: 600,
fast: 200,
// Default speed
_default: 400
},
step: {
opacity: function( fx ) {
jQuery.style( fx.elem, "opacity", fx.now );
},
_default: function( fx ) {
if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) {
fx.elem.style[ fx.prop ] = fx.now + fx.unit;
} else {
fx.elem[ fx.prop ] = fx.now;
}
}
}
});
// Ensure props that can't be negative don't go there on undershoot easing
jQuery.each( fxAttrs.concat.apply( [], fxAttrs ), function( i, prop ) {
// exclude marginTop, marginLeft, marginBottom and marginRight from this list
if ( prop.indexOf( "margin" ) ) {
jQuery.fx.step[ prop ] = function( fx ) {
jQuery.style( fx.elem, prop, Math.max(0, fx.now) + fx.unit );
};
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
}
// Try to restore the default display value of an element
function defaultDisplay( nodeName ) {
if ( !elemdisplay[ nodeName ] ) {
var body = document.body,
elem = jQuery( "<" + nodeName + ">" ).appendTo( body ),
display = elem.css( "display" );
elem.remove();
// If the simple way fails,
// get element's real default display by attaching it to a temp iframe
if ( display === "none" || display === "" ) {
// No iframe to use yet, so create it
if ( !iframe ) {
iframe = document.createElement( "iframe" );
iframe.frameBorder = iframe.width = iframe.height = 0;
}
body.appendChild( iframe );
// Create a cacheable copy of the iframe document on first call.
// IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML
// document to it; WebKit & Firefox won't allow reusing the iframe document.
if ( !iframeDoc || !iframe.createElement ) {
iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document;
iframeDoc.write( ( jQuery.support.boxModel ? "<!doctype html>" : "" ) + "<html><body>" );
iframeDoc.close();
}
elem = iframeDoc.createElement( nodeName );
iframeDoc.body.appendChild( elem );
display = jQuery.css( elem, "display" );
body.removeChild( iframe );
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return elemdisplay[ nodeName ];
}
var getOffset,
rtable = /^t(?:able|d|h)$/i,
rroot = /^(?:body|html)$/i;
if ( "getBoundingClientRect" in document.documentElement ) {
getOffset = function( elem, doc, docElem, box ) {
try {
box = elem.getBoundingClientRect();
} catch(e) {}
// Make sure we're not dealing with a disconnected DOM node
if ( !box || !jQuery.contains( docElem, elem ) ) {
return box ? { top: box.top, left: box.left } : { top: 0, left: 0 };
}
var body = doc.body,
win = getWindow( doc ),
clientTop = docElem.clientTop || body.clientTop || 0,
clientLeft = docElem.clientLeft || body.clientLeft || 0,
scrollTop = win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop,
scrollLeft = win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft,
top = box.top + scrollTop - clientTop,
left = box.left + scrollLeft - clientLeft;
return { top: top, left: left };
};
} else {
getOffset = function( elem, doc, docElem ) {
var computedStyle,
offsetParent = elem.offsetParent,
prevOffsetParent = elem,
body = doc.body,
defaultView = doc.defaultView,
prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle,
top = elem.offsetTop,
left = elem.offsetLeft;
while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) {
if ( jQuery.support.fixedPosition && prevComputedStyle.position === "fixed" ) {
break;
}
computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle;
top -= elem.scrollTop;
left -= elem.scrollLeft;
if ( elem === offsetParent ) {
top += elem.offsetTop;
left += elem.offsetLeft;
if ( jQuery.support.doesNotAddBorder && !(jQuery.support.doesAddBorderForTableAndCells && rtable.test(elem.nodeName)) ) {
top += parseFloat( computedStyle.borderTopWidth ) || 0;
left += parseFloat( computedStyle.borderLeftWidth ) || 0;
}
prevOffsetParent = offsetParent;
offsetParent = elem.offsetParent;
}
if ( jQuery.support.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) {
top += parseFloat( computedStyle.borderTopWidth ) || 0;
left += parseFloat( computedStyle.borderLeftWidth ) || 0;
}
prevComputedStyle = computedStyle;
}
if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) {
top += body.offsetTop;
left += body.offsetLeft;
}
if ( jQuery.support.fixedPosition && prevComputedStyle.position === "fixed" ) {
top += Math.max( docElem.scrollTop, body.scrollTop );
left += Math.max( docElem.scrollLeft, body.scrollLeft );
}
return { top: top, left: left };
};
}
jQuery.fn.offset = function( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var elem = this[0],
doc = elem && elem.ownerDocument;
if ( !doc ) {
return null;
}
if ( elem === doc.body ) {
return jQuery.offset.bodyOffset( elem );
}
return getOffset( elem, doc, doc.documentElement );
};
jQuery.offset = {
bodyOffset: function( body ) {
var top = body.offsetTop,
left = body.offsetLeft;
if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) {
top += parseFloat( jQuery.css(body, "marginTop") ) || 0;
left += parseFloat( jQuery.css(body, "marginLeft") ) || 0;
}
return { top: top, left: left };
},
setOffset: function( elem, options, i ) {
var position = jQuery.css( elem, "position" );
// set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
var curElem = jQuery( elem ),
curOffset = curElem.offset(),
curCSSTop = jQuery.css( elem, "top" ),
curCSSLeft = jQuery.css( elem, "left" ),
calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1,
props = {}, curPosition = {}, curTop, curLeft;
// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
position: function() {
if ( !this[0] ) {
return null;
}
var elem = this[0],
// Get *real* offsetParent
offsetParent = this.offsetParent(),
// Get correct offsets
offset = this.offset(),
parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset();
// Subtract element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0;
offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0;
// Add offsetParent borders
parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0;
parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0;
// Subtract the two offsets
return {
top: offset.top - parentOffset.top,
left: offset.left - parentOffset.left
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || document.body;
while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) {
var top = /Y/.test( prop );
jQuery.fn[ method ] = function( val ) {
return jQuery.access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? (prop in win) ? win[ prop ] :
jQuery.support.boxModel && win.document.documentElement[ method ] ||
win.document.body[ method ] :
elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : jQuery( win ).scrollLeft(),
top ? val : jQuery( win ).scrollTop()
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
// Create width, height, innerHeight, innerWidth, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
var clientProp = "client" + name,
scrollProp = "scroll" + name,
offsetProp = "offset" + name;
// innerHeight and innerWidth
jQuery.fn[ "inner" + name ] = function() {
var elem = this[0];
return elem ?
elem.style ?
parseFloat( jQuery.css( elem, type, "padding" ) ) :
this[ type ]() :
null;
};
// outerHeight and outerWidth
jQuery.fn[ "outer" + name ] = function( margin ) {
var elem = this[0];
return elem ?
elem.style ?
parseFloat( jQuery.css( elem, type, margin ? "margin" : "border" ) ) :
this[ type ]() :
null;
};
jQuery.fn[ type ] = function( value ) {
return jQuery.access( this, function( elem, type, value ) {
var doc, docElemProp, orig, ret;
if ( jQuery.isWindow( elem ) ) {
// 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat
doc = elem.document;
docElemProp = doc.documentElement[ clientProp ];
return jQuery.support.boxModel && docElemProp ||
doc.body && doc.body[ clientProp ] || docElemProp;
}
// Get document width or height
if ( elem.nodeType === 9 ) {
// Either scroll[Width/Height] or offset[Width/Height], whichever is greater
doc = elem.documentElement;
// when a window > document, IE6 reports a offset[Width/Height] > client[Width/Height]
// so we can't use max, as it'll choose the incorrect offset[Width/Height]
// instead we use the correct client[Width/Height]
// support:IE6
if ( doc[ clientProp ] >= doc[ scrollProp ] ) {
return doc[ clientProp ];
}
return Math.max(
elem.body[ scrollProp ], doc[ scrollProp ],
elem.body[ offsetProp ], doc[ offsetProp ]
);
}
// Get width or height on the element
if ( value === undefined ) {
orig = jQuery.css( elem, type );
ret = parseFloat( orig );
return jQuery.isNumeric( ret ) ? ret : orig;
}
// Set the width or height on the element
jQuery( elem ).css( type, value );
}, type, value, arguments.length, null );
};
});
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
// Expose jQuery as an AMD module, but only for AMD loaders that
// understand the issues with loading multiple versions of jQuery
// in a page that all might call define(). The loader will indicate
// they have special allowances for multiple jQuery versions by
// specifying define.amd.jQuery = true. Register as a named module,
// since jQuery can be concatenated with other files that may use define,
// but not use a proper concatenation script that understands anonymous
// AMD modules. A named AMD is safest and most robust way to register.
// Lowercase jquery is used because AMD module names are derived from
// file names, and jQuery is normally delivered in a lowercase file name.
// Do this after creating the global so that if an AMD module wants to call
// noConflict to hide this version of jQuery, it will work.
if ( typeof define === "function" && define.amd && define.amd.jQuery ) {
define( "jquery", [], function () { return jQuery; } );
}
})( window );