Bug 424813, Jquery test suite update, patch by harthur, r=sdwilsh

This commit is contained in:
Clint Talbert 2008-08-07 16:18:37 -07:00
Родитель af751d9b0a
Коммит 452fdfe51f
55 изменённых файлов: 7084 добавлений и 11249 удалений

Просмотреть файл

@ -0,0 +1,98 @@
== jQuery ChangeLog ==
== 1.2.2 ==
* show is now element aware (uses default display type instead of just forcing block)
* New special events api: jQuery.events.special
* ready is now a real event and can be bound, unbound and triggered.
* mouseenter and mouseleave now work on all supported browsers
* The hover helper method now uses the mouseenter and mouseleave events
* New offset test suite test/offset.html (requires your pop-up blocker to be disabled)
* Refactored the width and height methods (fixes lots of bugs)
* Fixed event memory leaks in IE (html, remove, empty also no longer leak memory)
* Fixed window/document width/height values
* Fixed event.pageX and event.pageY in IE
== 1.2 ==
=== 1.1.3 ===
* Always create an ActiveXObject when it is available instead of the XMLHttpRequest, even in IE7
* Removed XMLHttpRequest shadowing, may break code that relies on existence of that function for browser checking
* ...
=== 1.1.2 ===
* Event handlers (like element.onclick) are now removed when no more functions are bound to the event.
* Fixed DOM Manipulations for form elements.
* Fixed jQuery.isFunction to return false on nodes.
* Fixed jQuery.className.has, escaping regex characters in className (for metadata)
* Fixed an issue in IE where an event on a cloned element is fired during a .clone() inside of an event handler.
* Fixed IE ID selectors selecting by the name attribute.
* Change: Events are now internally stored in elem.$events rather than elem.events (due to a nasty bug relating to DOM 0 expandos).
* .attr('href') is now consistent in all browsers.
* @href is now consistent in all browsers.
* Fixed the slideDown flickering bug.
* Having a \r endline in $("...") caused a never-ending loop.
* Fixed IE6 AJAX memory leak
* Fixed bug in pushStack, reporting an element at [0] in a jQuery object with length 0
=== 1.1.1 ===
* Setting the numerical value of a css property failed, for example: .css("opacity",0.5) (also occurred with zIndex, fontWeight)
* Calling $(..., jqobj) with a context of a jQuery object failed.
* Accessing a property on an element that doesn't exist caused an error, for example: $("#foobar").attr("id")
* Calling .load() without a callback caused an error.
* You couldn't cancel an event that was triggered using .trigger() or .click() (for example).
* .add()ing a single DOM element to a jQuery object was broken.
* Passing in undefined values to a $.post() caused weird errors to occur.
* Accessing child nodes within an xml document didn't work properly.
* jQuery.isFunction() was unable to reliably determine a function, in a cross-browser way.
* Triggering a .click() failed in IE.
* Triggered click handlers were executed twice in most browsers.
* A newline passed into $(...) caused Firefox to go into a never-ending loop.
* Calling $.post() without any data caused an error.
* Calling a descendant selector after a child selector caused strange results, for example: $("ul > li ul")
* Triggered events did not occur if an event handler was not bound for that event.
== 1.1 ==
* Massive speed-ups (4x-10x) in the selector engine.
* You can now unbind event handlers from within themselves
* Added new .one( "type", fn ) method
* text(String) now escapes HTML
* Added attr(String,Function) to calculate the value
* Performming .click(), .blur(), .focus(), .submit() will actually trigger the browsers default action for those events.
* Added global settings for AJAX (in addition to timeout), use $.ajaxSetup() to modify them
* Implemented a better error handling for ajax requests. Exceptions caused by dropping connections are now handled, too.
* Improved event fixing (Opera provides event.srcElement, must ignore it if target is available; only create pageX if clientX is available)
* Fixed nth-child selectors to start on the right number
* jQuery is no longer destructive. Doing var a = $("a"); a.find("span"); does not change the original "a" variable.
* Fixed synchronous requests
* Fixed ID with context selectors (eg. div #id doesn't ignore "div" anymore)
* Fixed docs for html(): Now mentions that is not available for XML documents
* Improved AJAX docs (eg. more examples for $.ajax)
* Documented filter(Function), a very powerful approach for custom filtering
* Improved docs for FX module, merging method descriptions and marking optional arguments
* Improved docs for append, prepend, before and after, merging the three pairs into one
* Improved show/hide animations to show only hidden and hide only visible elements
* Removed .oneEvent() and .unEvent() helper methods.
* Removed all CSS helper methods.
* Removed most attribute helper methods.
* Removed the (undocumented) .find( "selector", fn ) for all destructive methods.
* $.get, $.getIfModified, $.post, $.getScript and $.getJSON now all pass through the XMLHttpRequest as returned by $.ajax
== 1.0.4 ==
* Tons of bug fixes
* Extensions to $.ajax: $.ajax accepts additonal options: beforeSend, async and processData; returns XMLHttpRequest to allow manual aborting of requests, see docs for details
* AJAX module: the public $.ajax API is now used internally (for $.get/$.post etc.); loading scripts works now much more reliable on all browers except Safari
* New global ajax handler: ajaxSend - called before an ajax request is sent
* Extensions to global ajax handlers: ajaxSend, ajaxSuccess, ajaxError and ajaxComplete get XMLHttpRequest and settings passed as arguments
* Extensions to event handling: pageX and pageY are available x-browser (IE does not provide native pageX/Y)
* Improved docs: $(String) method has now two seperate descriptions, one for selecting elements, one for creating (html on-the-fly)
* FX module: Most inline stlyes added by animations are now removed when the animation is complete, eg. height style when animating height (exception: display styles)
* Added note to attr(String, Object) about issues with setting the name property on input elements
* Seperated internal stuff from get() into set()
* Merged the two API examples for each() into one more precise example
* Improved docs for $.browser and added docs for $.boxModel
* Docs for the jQuery constructor $() were improved: There is now $(String expression[, Object context]) and $(String html)

Просмотреть файл

@ -1,4 +1,4 @@
Copyright (c) 2007 John Resig, http://jquery.com/
Copyright (c) 2008 John Resig, http://jquery.com/
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the

Просмотреть файл

@ -45,16 +45,13 @@ include $(DEPTH)/config/autoconf.mk
DIRS = \
dist \
src \
test \
$(NULL)
include $(topsrcdir)/config/rules.mk
_TEST_FILES = \
GPL-LICENSE.txt \
manifest.json \
MIT-LICENSE.txt \
test_jQuery.html \
$(NULL)

6673
dom/tests/mochitest/ajax/jquery/dist/jquery.js поставляемый

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -1,57 +0,0 @@
#
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is
# Mozilla Foundation.
# Portions created by the Initial Developer are Copyright (C) 2007
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
#
# Alternatively, the contents of this file may be used under the terms of
# either of the GNU General Public License Version 2 or later (the "GPL"),
# or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
DEPTH = ../../../../../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
relativesrcdir = dom/tests/mochitest/ajax/jquery/src/ajax
include $(DEPTH)/config/autoconf.mk
DIRS = \
$(NULL)
include $(topsrcdir)/config/rules.mk
_TEST_FILES = \
ajax.js \
ajaxTest.js \
$(NULL)
libs:: $(_TEST_FILES)
$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/tests/$(relativesrcdir)

Просмотреть файл

@ -1,838 +0,0 @@
jQuery.fn.extend({
/**
* Load HTML from a remote file and inject it into the DOM, only if it's
* been modified by the server.
*
* @example $("#feeds").loadIfModified("feeds.html");
* @before <div id="feeds"></div>
* @result <div id="feeds"><b>45</b> feeds found.</div>
*
* @name loadIfModified
* @type jQuery
* @param String url The URL of the HTML file to load.
* @param Map params (optional) Key/value pairs that will be sent to the server.
* @param Function callback (optional) A function to be executed whenever the data is loaded (parameters: responseText, status and response itself).
* @cat Ajax
*/
loadIfModified: function( url, params, callback ) {
this.load( url, params, callback, 1 );
},
/**
* Load HTML from a remote file and inject it into the DOM.
*
* Note: Avoid to use this to load scripts, instead use $.getScript.
* IE strips script tags when there aren't any other characters in front of it.
*
* @example $("#feeds").load("feeds.html");
* @before <div id="feeds"></div>
* @result <div id="feeds"><b>45</b> feeds found.</div>
*
* @example $("#feeds").load("feeds.html",
* {limit: 25},
* function() { alert("The last 25 entries in the feed have been loaded"); }
* );
* @desc Same as above, but with an additional parameter
* and a callback that is executed when the data was loaded.
*
* @name load
* @type jQuery
* @param String url The URL of the HTML file to load.
* @param Object params (optional) A set of key/value pairs that will be sent as data to the server.
* @param Function callback (optional) A function to be executed whenever the data is loaded (parameters: responseText, status and response itself).
* @cat Ajax
*/
load: function( url, params, callback, ifModified ) {
if ( jQuery.isFunction( url ) )
return this.bind("load", url);
callback = callback || function(){};
// 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 = null;
// Otherwise, build a param string
} else {
params = jQuery.param( params );
type = "POST";
}
var self = this;
// Request the remote document
jQuery.ajax({
url: url,
type: type,
data: params,
ifModified: ifModified,
complete: function(res, status){
if ( status == "success" || !ifModified && status == "notmodified" )
// Inject the HTML into all the matched elements
self.attr("innerHTML", res.responseText)
// Execute all the scripts inside of the newly-injected HTML
.evalScripts()
// Execute callback
.each( callback, [res.responseText, status, res] );
else
callback.apply( self, [res.responseText, status, res] );
}
});
return this;
},
/**
* Serializes a set of input elements into a string of data.
* This will serialize all given elements.
*
* A serialization similar to the form submit of a browser is
* provided by the [http://www.malsup.com/jquery/form/ Form Plugin].
* It also takes multiple-selects
* into account, while this method recognizes only a single option.
*
* @example $("input[@type=text]").serialize();
* @before <input type='text' name='name' value='John'/>
* <input type='text' name='location' value='Boston'/>
* @after name=John&amp;location=Boston
* @desc Serialize a selection of input elements to a string
*
* @name serialize
* @type String
* @cat Ajax
*/
serialize: function() {
return jQuery.param( this );
},
/**
* Evaluate all script tags inside this jQuery. If they have a src attribute,
* the script is loaded, otherwise it's content is evaluated.
*
* @name evalScripts
* @type jQuery
* @private
* @cat Ajax
*/
evalScripts: function() {
return this.find("script").each(function(){
if ( this.src )
jQuery.getScript( this.src );
else
jQuery.globalEval( this.text || this.textContent || this.innerHTML || "" );
}).end();
}
});
// Attach a bunch of functions for handling common AJAX events
/**
* Attach a function to be executed whenever an AJAX request begins
* and there is none already active.
*
* @example $("#loading").ajaxStart(function(){
* $(this).show();
* });
* @desc Show a loading message whenever an AJAX request starts
* (and none is already active).
*
* @name ajaxStart
* @type jQuery
* @param Function callback The function to execute.
* @cat Ajax
*/
/**
* Attach a function to be executed whenever all AJAX requests have ended.
*
* @example $("#loading").ajaxStop(function(){
* $(this).hide();
* });
* @desc Hide a loading message after all the AJAX requests have stopped.
*
* @name ajaxStop
* @type jQuery
* @param Function callback The function to execute.
* @cat Ajax
*/
/**
* Attach a function to be executed whenever an AJAX request completes.
*
* The XMLHttpRequest and settings used for that request are passed
* as arguments to the callback.
*
* @example $("#msg").ajaxComplete(function(request, settings){
* $(this).append("<li>Request Complete.</li>");
* });
* @desc Show a message when an AJAX request completes.
*
* @name ajaxComplete
* @type jQuery
* @param Function callback The function to execute.
* @cat Ajax
*/
/**
* Attach a function to be executed whenever an AJAX request completes
* successfully.
*
* The XMLHttpRequest and settings used for that request are passed
* as arguments to the callback.
*
* @example $("#msg").ajaxSuccess(function(request, settings){
* $(this).append("<li>Successful Request!</li>");
* });
* @desc Show a message when an AJAX request completes successfully.
*
* @name ajaxSuccess
* @type jQuery
* @param Function callback The function to execute.
* @cat Ajax
*/
/**
* Attach a function to be executed whenever an AJAX request fails.
*
* The XMLHttpRequest and settings used for that request are passed
* as arguments to the callback. A third argument, an exception object,
* is passed if an exception occured while processing the request.
*
* @example $("#msg").ajaxError(function(request, settings){
* $(this).append("<li>Error requesting page " + settings.url + "</li>");
* });
* @desc Show a message when an AJAX request fails.
*
* @name ajaxError
* @type jQuery
* @param Function callback The function to execute.
* @cat Ajax
*/
/**
* Attach a function to be executed before an AJAX request is sent.
*
* The XMLHttpRequest and settings used for that request are passed
* as arguments to the callback.
*
* @example $("#msg").ajaxSend(function(request, settings){
* $(this).append("<li>Starting request at " + settings.url + "</li>");
* });
* @desc Show a message before an AJAX request is sent.
*
* @name ajaxSend
* @type jQuery
* @param Function callback The function to execute.
* @cat Ajax
*/
jQuery.each( "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","), function(i,o){
jQuery.fn[o] = function(f){
return this.bind(o, f);
};
});
jQuery.extend({
/**
* Load a remote page using an HTTP GET request.
*
* This is an easy way to send a simple GET request to a server
* without having to use the more complex $.ajax function. It
* allows a single callback function to be specified that will
* be executed when the request is complete (and only if the response
* has a successful response code). If you need to have both error
* and success callbacks, you may want to use $.ajax.
*
* @example $.get("test.cgi");
*
* @example $.get("test.cgi", { name: "John", time: "2pm" } );
*
* @example $.get("test.cgi", function(data){
* alert("Data Loaded: " + data);
* });
*
* @example $.get("test.cgi",
* { name: "John", time: "2pm" },
* function(data){
* alert("Data Loaded: " + data);
* }
* );
*
* @name $.get
* @type XMLHttpRequest
* @param String url The URL of the page to load.
* @param Map params (optional) Key/value pairs that will be sent to the server.
* @param Function callback (optional) A function to be executed whenever the data is loaded successfully.
* @cat Ajax
*/
get: function( url, data, callback, type, ifModified ) {
// shift arguments if data argument was ommited
if ( jQuery.isFunction( data ) ) {
callback = data;
data = null;
}
return jQuery.ajax({
type: "GET",
url: url,
data: data,
success: callback,
dataType: type,
ifModified: ifModified
});
},
/**
* Load a remote page using an HTTP GET request, only if it hasn't
* been modified since it was last retrieved.
*
* @example $.getIfModified("test.html");
*
* @example $.getIfModified("test.html", { name: "John", time: "2pm" } );
*
* @example $.getIfModified("test.cgi", function(data){
* alert("Data Loaded: " + data);
* });
*
* @example $.getifModified("test.cgi",
* { name: "John", time: "2pm" },
* function(data){
* alert("Data Loaded: " + data);
* }
* );
*
* @name $.getIfModified
* @type XMLHttpRequest
* @param String url The URL of the page to load.
* @param Map params (optional) Key/value pairs that will be sent to the server.
* @param Function callback (optional) A function to be executed whenever the data is loaded successfully.
* @cat Ajax
*/
getIfModified: function( url, data, callback, type ) {
return jQuery.get(url, data, callback, type, 1);
},
/**
* Loads, and executes, a remote JavaScript file using an HTTP GET request.
*
* Warning: Safari <= 2.0.x is unable to evaluate scripts in a global
* context synchronously. If you load functions via getScript, make sure
* to call them after a delay.
*
* @example $.getScript("test.js");
*
* @example $.getScript("test.js", function(){
* alert("Script loaded and executed.");
* });
*
* @name $.getScript
* @type XMLHttpRequest
* @param String url The URL of the page to load.
* @param Function callback (optional) A function to be executed whenever the data is loaded successfully.
* @cat Ajax
*/
getScript: function( url, callback ) {
return jQuery.get(url, null, callback, "script");
},
/**
* Load JSON data using an HTTP GET request.
*
* @example $.getJSON("test.js", function(json){
* alert("JSON Data: " + json.users[3].name);
* });
*
* @example $.getJSON("test.js",
* { name: "John", time: "2pm" },
* function(json){
* alert("JSON Data: " + json.users[3].name);
* }
* );
*
* @name $.getJSON
* @type XMLHttpRequest
* @param String url The URL of the page to load.
* @param Map params (optional) Key/value pairs that will be sent to the server.
* @param Function callback A function to be executed whenever the data is loaded successfully.
* @cat Ajax
*/
getJSON: function( url, data, callback ) {
return jQuery.get(url, data, callback, "json");
},
/**
* Load a remote page using an HTTP POST request.
*
* @example $.post("test.cgi");
*
* @example $.post("test.cgi", { name: "John", time: "2pm" } );
*
* @example $.post("test.cgi", function(data){
* alert("Data Loaded: " + data);
* });
*
* @example $.post("test.cgi",
* { name: "John", time: "2pm" },
* function(data){
* alert("Data Loaded: " + data);
* }
* );
*
* @name $.post
* @type XMLHttpRequest
* @param String url The URL of the page to load.
* @param Map params (optional) Key/value pairs that will be sent to the server.
* @param Function callback (optional) A function to be executed whenever the data is loaded successfully.
* @cat Ajax
*/
post: function( url, data, callback, type ) {
if ( jQuery.isFunction( data ) ) {
callback = data;
data = {};
}
return jQuery.ajax({
type: "POST",
url: url,
data: data,
success: callback,
dataType: type
});
},
/**
* Set the timeout in milliseconds of all AJAX requests to a specific amount of time.
* This will make all future AJAX requests timeout after a specified amount
* of time.
*
* Set to null or 0 to disable timeouts (default).
*
* You can manually abort requests with the XMLHttpRequest's (returned by
* all ajax functions) abort() method.
*
* Deprecated. Use $.ajaxSetup instead.
*
* @example $.ajaxTimeout( 5000 );
* @desc Make all AJAX requests timeout after 5 seconds.
*
* @name $.ajaxTimeout
* @type undefined
* @param Number time How long before an AJAX request times out, in milliseconds.
* @cat Ajax
*/
ajaxTimeout: function( timeout ) {
jQuery.ajaxSettings.timeout = timeout;
},
/**
* Setup global settings for AJAX requests.
*
* See $.ajax for a description of all available options.
*
* @example $.ajaxSetup( {
* url: "/xmlhttp/",
* global: false,
* type: "POST"
* } );
* $.ajax({ data: myData });
* @desc Sets the defaults for AJAX requests to the url "/xmlhttp/",
* disables global handlers and uses POST instead of GET. The following
* AJAX requests then sends some data without having to set anything else.
*
* @name $.ajaxSetup
* @type undefined
* @param Map settings Key/value pairs to use for all AJAX requests
* @cat Ajax
*/
ajaxSetup: function( settings ) {
jQuery.extend( jQuery.ajaxSettings, settings );
},
ajaxSettings: {
global: true,
type: "GET",
timeout: 0,
contentType: "application/x-www-form-urlencoded",
processData: true,
async: true,
data: null
},
// Last-Modified header cache for next request
lastModified: {},
/**
* Load a remote page using an HTTP request.
*
* This is jQuery's low-level AJAX implementation. See $.get, $.post etc. for
* higher-level abstractions that are often easier to understand and use,
* but don't offer as much functionality (such as error callbacks).
*
* $.ajax() returns the XMLHttpRequest that it creates. In most cases you won't
* need that object to manipulate directly, but it is available if you need to
* abort the request manually.
*
* '''Note:''' If you specify the dataType option described below, make sure
* the server sends the correct MIME type in the response (eg. xml as "text/xml").
* Sending the wrong MIME type can lead to unexpected problems in your script.
* See [[Specifying the Data Type for AJAX Requests]] for more information.
*
* Supported datatypes are (see dataType option):
*
* "xml": Returns a XML document that can be processed via jQuery.
*
* "html": Returns HTML as plain text, included script tags are evaluated.
*
* "script": Evaluates the response as Javascript and returns it as plain text.
*
* "json": Evaluates the response as JSON and returns a Javascript Object
*
* $.ajax() takes one argument, an object of key/value pairs, that are
* used to initalize and handle the request. These are all the key/values that can
* be used:
*
* (String) url - The URL to request.
*
* (String) type - The type of request to make ("POST" or "GET"), default is "GET".
*
* (String) dataType - The type of data that you're expecting back from
* the server. No default: If the server sends xml, the responseXML, otherwise
* the responseText is passed to the success callback.
*
* (Boolean) ifModified - Allow the request to be successful only if the
* response has changed since the last request. This is done by checking the
* Last-Modified header. Default value is false, ignoring the header.
*
* (Number) timeout - Local timeout in milliseconds to override global timeout, eg. to give a
* single request a longer timeout while all others timeout after 1 second.
* See $.ajaxTimeout() for global timeouts.
*
* (Boolean) global - Whether to trigger global AJAX event handlers for
* this request, default is true. Set to false to prevent that global handlers
* like ajaxStart or ajaxStop are triggered.
*
* (Function) error - A function to be called if the request fails. The
* function gets passed tree arguments: The XMLHttpRequest object, a
* string describing the type of error that occurred and an optional
* exception object, if one occured.
*
* (Function) success - A function to be called if the request succeeds. The
* function gets passed one argument: The data returned from the server,
* formatted according to the 'dataType' parameter.
*
* (Function) complete - A function to be called when the request finishes. The
* function gets passed two arguments: The XMLHttpRequest object and a
* string describing the type of success of the request.
*
* (Object|String) data - Data to be sent to the server. Converted to a query
* string, if not already a string. Is appended to the url for GET-requests.
* See processData option to prevent this automatic processing.
*
* (String) contentType - When sending data to the server, use this content-type.
* Default is "application/x-www-form-urlencoded", which is fine for most cases.
*
* (Boolean) processData - By default, data passed in to the data option as an object
* other as string will be processed and transformed into a query string, fitting to
* the default content-type "application/x-www-form-urlencoded". If you want to send
* DOMDocuments, set this option to false.
*
* (Boolean) async - By default, all requests are sent asynchronous (set to true).
* If you need synchronous requests, set this option to false.
*
* (Function) beforeSend - A pre-callback to set custom headers etc., the
* XMLHttpRequest is passed as the only argument.
*
* @example $.ajax({
* type: "GET",
* url: "test.js",
* dataType: "script"
* })
* @desc Load and execute a JavaScript file.
*
* @example $.ajax({
* type: "POST",
* url: "some.php",
* data: "name=John&location=Boston",
* success: function(msg){
* alert( "Data Saved: " + msg );
* }
* });
* @desc Save some data to the server and notify the user once its complete.
*
* @example var html = $.ajax({
* url: "some.php",
* async: false
* }).responseText;
* @desc Loads data synchronously. Blocks the browser while the requests is active.
* It is better to block user interaction by other means when synchronization is
* necessary.
*
* @example var xmlDocument = [create xml document];
* $.ajax({
* url: "page.php",
* processData: false,
* data: xmlDocument,
* success: handleResponse
* });
* @desc Sends an xml document as data to the server. By setting the processData
* option to false, the automatic conversion of data to strings is prevented.
*
* @name $.ajax
* @type XMLHttpRequest
* @param Map properties Key/value pairs to initialize the request with.
* @cat Ajax
* @see ajaxSetup(Map)
*/
ajax: function( s ) {
// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s);
// if data available
if ( s.data ) {
// convert data if not already a string
if (s.processData && typeof s.data != "string")
s.data = jQuery.param(s.data);
// append data to url for get requests
if( s.type.toLowerCase() == "get" ) {
// "?" + data or "&" + data (in case there are already params)
s.url += ((s.url.indexOf("?") > -1) ? "&" : "?") + s.data;
// IE likes to send both get and post data, prevent this
s.data = null;
}
}
// Watch for a new set of requests
if ( s.global && ! jQuery.active++ )
jQuery.event.trigger( "ajaxStart" );
var requestDone = false;
// Create the request object; Microsoft failed to properly
// implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
var xml = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
// Open the socket
xml.open(s.type, s.url, s.async);
// Set the correct header, if data is being sent
if ( s.data )
xml.setRequestHeader("Content-Type", s.contentType);
// Set the If-Modified-Since header, if ifModified mode.
if ( s.ifModified )
xml.setRequestHeader("If-Modified-Since",
jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
// Set header so the called script knows that it's an XMLHttpRequest
xml.setRequestHeader("X-Requested-With", "XMLHttpRequest");
// Allow custom headers/mimetypes
if( s.beforeSend )
s.beforeSend(xml);
if ( s.global )
jQuery.event.trigger("ajaxSend", [xml, s]);
// Wait for a response to come back
var onreadystatechange = function(isTimeout){
// The transfer is complete and the data is available, or the request timed out
if ( xml && (xml.readyState == 4 || isTimeout == "timeout") ) {
requestDone = true;
// clear poll interval
if (ival) {
clearInterval(ival);
ival = null;
}
var status;
try {
status = jQuery.httpSuccess( xml ) && isTimeout != "timeout" ?
s.ifModified && jQuery.httpNotModified( xml, s.url ) ? "notmodified" : "success" : "error";
// Make sure that the request was successful or notmodified
if ( status != "error" ) {
// Cache Last-Modified header, if ifModified mode.
var modRes;
try {
modRes = xml.getResponseHeader("Last-Modified");
} catch(e) {} // swallow exception thrown by FF if header is not available
if ( s.ifModified && modRes )
jQuery.lastModified[s.url] = modRes;
// process the data (runs the xml through httpData regardless of callback)
var data = jQuery.httpData( xml, s.dataType );
// If a local callback was specified, fire it and pass it the data
if ( s.success )
s.success( data, status );
// Fire the global callback
if( s.global )
jQuery.event.trigger( "ajaxSuccess", [xml, s] );
} else
jQuery.handleError(s, xml, status);
} catch(e) {
status = "error";
jQuery.handleError(s, xml, status, e);
}
// The request was completed
if( s.global )
jQuery.event.trigger( "ajaxComplete", [xml, s] );
// Handle the global AJAX counter
if ( s.global && ! --jQuery.active )
jQuery.event.trigger( "ajaxStop" );
// Process result
if ( s.complete )
s.complete(xml, status);
// Stop memory leaks
if(s.async)
xml = null;
}
};
// don't attach the handler to the request, just poll it instead
var ival = setInterval(onreadystatechange, 13);
// Timeout checker
if ( s.timeout > 0 )
setTimeout(function(){
// Check to see if the request is still happening
if ( xml ) {
// Cancel the request
xml.abort();
if( !requestDone )
onreadystatechange( "timeout" );
}
}, s.timeout);
// Send the data
try {
xml.send(s.data);
} catch(e) {
jQuery.handleError(s, xml, null, e);
}
// firefox 1.5 doesn't fire statechange for sync requests
if ( !s.async )
onreadystatechange();
// return XMLHttpRequest to allow aborting the request etc.
return xml;
},
handleError: function( s, xml, status, e ) {
// If a local callback was specified, fire it
if ( s.error ) s.error( xml, status, e );
// Fire the global callback
if ( s.global )
jQuery.event.trigger( "ajaxError", [xml, s, e] );
},
// Counter for holding the number of active queries
active: 0,
// Determines if an XMLHttpRequest was successful or not
httpSuccess: function( r ) {
try {
return !r.status && location.protocol == "file:" ||
( r.status >= 200 && r.status < 300 ) || r.status == 304 ||
jQuery.browser.safari && r.status == undefined;
} catch(e){}
return false;
},
// Determines if an XMLHttpRequest returns NotModified
httpNotModified: function( xml, url ) {
try {
var xmlRes = xml.getResponseHeader("Last-Modified");
// Firefox always returns 200. check Last-Modified date
return xml.status == 304 || xmlRes == jQuery.lastModified[url] ||
jQuery.browser.safari && xml.status == undefined;
} catch(e){}
return false;
},
/* Get the data out of an XMLHttpRequest.
* Return parsed XML if content-type header is "xml" and type is "xml" or omitted,
* otherwise return plain text.
* (String) data - The type of data that you're expecting back,
* (e.g. "xml", "html", "script")
*/
httpData: function( r, type ) {
var ct = r.getResponseHeader("content-type");
var data = !type && ct && ct.indexOf("xml") >= 0;
data = type == "xml" || data ? r.responseXML : r.responseText;
// If the type is "script", eval it in global context
if ( type == "script" )
jQuery.globalEval( data );
// Get the JavaScript object, if JSON is used.
if ( type == "json" )
data = eval("(" + data + ")");
// evaluate scripts within html
if ( type == "html" )
jQuery("<div>").html(data).evalScripts();
return data;
},
// Serialize an array of form elements or a set of
// key/values into a query string
param: function( a ) {
var s = [];
// If an array was passed in, assume that it is an array
// of form elements
if ( a.constructor == Array || a.jquery )
// Serialize the form elements
jQuery.each( a, function(){
s.push( encodeURIComponent(this.name) + "=" + encodeURIComponent( this.value ) );
});
// Otherwise, assume that it's an object of key/value pairs
else
// Serialize the key/values
for ( var j in a )
// If the value is an array then the key names need to be repeated
if ( a[j] && a[j].constructor == Array )
jQuery.each( a[j], function(){
s.push( encodeURIComponent(j) + "=" + encodeURIComponent( this ) );
});
else
s.push( encodeURIComponent(j) + "=" + encodeURIComponent( a[j] ) );
// Return the resulting serialization
return s.join("&");
},
// evalulates a script in global context
// not reliable for safari
globalEval: function( data ) {
if ( window.execScript )
window.execScript( data );
else if ( jQuery.browser.safari )
// safari doesn't provide a synchronous global eval
window.setTimeout( data, 0 );
else
eval.call( window, data );
}
});

Просмотреть файл

@ -1,395 +0,0 @@
module("ajax");
if ( location.protocol != "file:" ) {
test("serialize()", function() {
expect(1);
var data = $(':input').not('button').serialize();
// ignore button, IE takes text content as value, not relevant for this test
ok( data == 'action=Test&text2=Test&radio1=on&radio2=on&check=on&=on&hidden=&foo%5Bbar%5D=&name=name&=foobar&select1=&select2=3&select3=1', 'Check form serialization as query string' );
});
test("param", function() {
expect(4);
var params = {foo:"bar", baz:42, quux:"All your base are belong to us"};
ok( $.param(params) == "foo=bar&baz=42&quux=All%20your%20base%20are%20belong%20to%20us", "simple" );
params = {someName: [1, 2, 3], regularThing: "blah" };
ok( $.param(params) == "someName=1&someName=2&someName=3&regularThing=blah", "with array" );
params = {"foo[]":["baz", 42, "All your base are belong to us"]};
ok( $.param(params) == "foo%5B%5D=baz&foo%5B%5D=42&foo%5B%5D=All%20your%20base%20are%20belong%20to%20us", "more array" );
params = {"foo[bar]":"baz", "foo[beep]":42, "foo[quux]":"All your base are belong to us"};
ok( $.param(params) == "foo%5Bbar%5D=baz&foo%5Bbeep%5D=42&foo%5Bquux%5D=All%20your%20base%20are%20belong%20to%20us", "even more arrays" );
});
test("pass-through request object", function() {
expect(7);
stop(true);
var count = 0;
var success = function() {
if(count++ == 6)
start();
}
var target = "data/name.php";
ok( $.get(url(target), success), "get" );
ok( $.getIfModified(url(target), success), "getIfModified" );
ok( $.post(url(target), success), "post" );
ok( $.getScript(url("data/test.js"), success), "script" );
ok( $.getJSON(url("data/json.php"), success), "json" );
ok( $.ajax({url: url(target), success: success}), "generic" );
});
test("synchronous request", function() {
ok( /^{ "data"/.test( $.ajax({url: url("data/json.php"), async: false}).responseText ), "check returned text" );
});
test("synchronous request with callbacks", function() {
expect(2);
var result;
$.ajax({url: url("data/json.php"), async: false, success: function(data) { ok(true, "sucess callback executed"); result = data; } });
ok( /^{ "data"/.test( result ), "check returned text" );
});
test("load(String, Object, Function) - simple: inject text into DOM", function() {
expect(2);
stop();
$('#first').load(url("data/name.php"), function() {
ok( /^ERROR/.test($('#first').text()), 'Check if content was injected into the DOM' );
start();
});
});
test("load(String, Object, Function) - inject without callback", function() {
expect(1);
stop(true); // check if load can be called with only url
$('#first').load("data/name.php");
});
test("load(String, Object, Function) - check scripts", function() {
expect(7);
stop();
window.testFoo = undefined;
window.foobar = null;
var verifyEvaluation = function() {
ok( foobar == "bar", 'Check if script src was evaluated after load' );
ok( $('#ap').html() == 'bar', 'Check if script evaluation has modified DOM');
start();
};
$('#first').load(url('data/test.php'), function() {
ok( $('#first').html().match(/^html text/), 'Check content after loading html' );
ok( $('#foo').html() == 'foo', 'Check if script evaluation has modified DOM');
ok( testFoo == "foo", 'Check if script was evaluated after load' );
setTimeout(verifyEvaluation, 600);
});
});
test("load(String, Object, Function) - check file with only a script tag", function() {
expect(3);
stop();
testFoo = undefined;
$('#first').load(url('data/test2.php'), function() {
ok( $('#foo').html() == 'foo', 'Check if script evaluation has modified DOM');
ok( testFoo == "foo", 'Check if script was evaluated after load' );
start();
});
});
test("test global handlers - success", function() {
expect(8);
stop();
var counter = { complete: 0, success: 0, error: 0, send: 0 },
success = function() { counter.success++ },
error = function() { counter.error++ },
complete = function() { counter.complete++ },
send = function() { counter.send++ };
$('#foo').ajaxStart(complete).ajaxStop(complete).ajaxSend(send).ajaxComplete(complete).ajaxError(error).ajaxSuccess(success);
// start with successful test
$.ajax({url: url("data/name.php"), beforeSend: send, success: success, error: error, complete: function() {
ok( counter.error == 0, 'Check succesful request' );
ok( counter.success == 2, 'Check succesful request' );
ok( counter.complete == 3, 'Check succesful request' );
ok( counter.send == 2, 'Check succesful request' );
counter.error = counter.success = counter.complete = counter.send = 0;
$.ajaxTimeout(500);
$.ajax({url: url("data/name.php?wait=5"), beforeSend: send, success: success, error: error, complete: function() {
ok( counter.error == 2, 'Check failed request' );
ok( counter.success == 0, 'Check failed request' );
ok( counter.complete == 3, 'Check failed request' );
ok( counter.send == 2, 'Check failed request' );
start();
}});
}});
});
test("test global handlers - failure", function() {
expect(8);
stop();
var counter = { complete: 0, success: 0, error: 0, send: 0 },
success = function() { counter.success++ },
error = function() { counter.error++ },
complete = function() { counter.complete++ },
send = function() { counter.send++ };
$.ajaxTimeout(0);
$('#foo').ajaxStart(complete).ajaxStop(complete).ajaxSend(send).ajaxComplete(complete).ajaxError(error).ajaxSuccess(success);
$.ajax({url: url("data/name.php"), global: false, beforeSend: send, success: success, error: error, complete: function() {
ok( counter.error == 0, 'Check sucesful request without globals' );
ok( counter.success == 1, 'Check sucesful request without globals' );
ok( counter.complete == 0, 'Check sucesful request without globals' );
ok( counter.send == 1, 'Check sucesful request without globals' );
counter.error = counter.success = counter.complete = counter.send = 0;
$.ajaxTimeout(500);
$.ajax({url: url("data/name.php?wait=5"), global: false, beforeSend: send, success: success, error: error, complete: function() {
var x = counter;
ok( counter.error == 1, 'Check failed request without globals' );
ok( counter.success == 0, 'Check failed request without globals' );
ok( counter.complete == 0, 'Check failed request without globals' );
ok( counter.send == 1, 'Check failed request without globals' );
start();
}});
}});
});
test("$.get(String, Hash, Function) - parse xml and use text() on nodes", function() {
expect(2);
stop();
$.get(url('data/dashboard.xml'), function(xml) {
var content = [];
$('tab', xml).each(function() {
content.push($(this).text());
});
ok( content[0] == 'blabla', 'Check first tab');
ok( content[1] == 'blublu', 'Check second tab');
start();
});
});
test("$.getIfModified(String, Hash, Function)", function() {
expect(1);
stop();
$.getIfModified(url("data/name.php"), function(msg) {
ok( /^ERROR/.test(msg), 'Check ifModified' );
start();
});
});
test("$.getScript(String, Function) - with callback", function() {
expect(2);
stop();
$.getScript(url("data/test.js"), function() {
ok( foobar == "bar", 'Check if script was evaluated' );
setTimeout(start, 100);
});
});
test("$.getScript(String, Function) - no callback", function() {
expect(1);
stop(true);
$.getScript(url("data/test.js"));
});
test("$.getJSON(String, Hash, Function) - JSON array", function() {
expect(4);
stop();
$.getJSON(url("data/json.php"), {json: "array"}, function(json) {
ok( json[0].name == 'John', 'Check JSON: first, name' );
ok( json[0].age == 21, 'Check JSON: first, age' );
ok( json[1].name == 'Peter', 'Check JSON: second, name' );
ok( json[1].age == 25, 'Check JSON: second, age' );
start();
});
});
test("$.getJSON(String, Hash, Function) - JSON object", function() {
expect(2);
stop();
$.getJSON(url("data/json.php"), function(json) {
ok( json.data.lang == 'en', 'Check JSON: lang' );
ok( json.data.length == 25, 'Check JSON: length' );
start();
});
});
test("$.post(String, Hash, Function) - simple with xml", function() {
expect(2);
stop();
$.post(url("data/name.php"), {xml: "5-2"}, function(xml){
$('math', xml).each(function() {
ok( $('calculation', this).text() == '5-2', 'Check for XML' );
ok( $('result', this).text() == '3', 'Check for XML' );
});
start();
});
});
test("$.ajaxTimeout(Number) - with global timeout", function() {
stop();
var passed = 0;
var timeout;
$.ajaxTimeout(1000);
var pass = function() {
passed++;
if(passed == 2) {
ok( true, 'Check local and global callbacks after timeout' );
clearTimeout(timeout);
$('#main').unbind("ajaxError");
start();
}
};
var fail = function() {
ok( false, 'Check for timeout failed' );
start();
};
timeout = setTimeout(fail, 1500);
$('#main').ajaxError(pass);
$.ajax({
type: "GET",
url: url("data/name.php?wait=5"),
error: pass,
success: fail
});
// reset timeout
$.ajaxTimeout(0);
});
test("$.ajaxTimeout(Number) with localtimeout", function() {
stop(); $.ajaxTimeout(50);
$.ajax({
type: "GET",
timeout: 5000,
url: url("data/name.php?wait=1"),
error: function() {
ok( false, 'Check for local timeout failed' );
start();
},
success: function() {
ok( true, 'Check for local timeout' );
start();
}
});
// reset timeout
$.ajaxTimeout(0);
});
test("$.ajax - simple get", function() {
expect(1);
stop();
$.ajax({
type: "GET",
url: url("data/name.php?name=foo"),
success: function(msg){
ok( msg == 'bar', 'Check for GET' );
start();
}
});
});
test("$.ajax - simple post", function() {
expect(1);
stop();
$.ajax({
type: "POST",
url: url("data/name.php"),
data: "name=peter",
success: function(msg){
ok( msg == 'pan', 'Check for POST' );
start();
}
});
});
test("$.ajax - dataType html", function() {
expect(5);
stop();
foobar = null;
testFoo = undefined;
var verifyEvaluation = function() {
ok( foobar == "bar", 'Check if script src was evaluated for datatype html' );
start();
};
$.ajax({
dataType: "html",
url: url("data/test.php"),
success: function(data) {
ok( data.match(/^html text/), 'Check content for datatype html' );
ok( testFoo == "foo", 'Check if script was evaluated for datatype html' );
setTimeout(verifyEvaluation, 600);
}
});
});
test("$.ajax - xml: non-namespace elements inside namespaced elements", function() {
expect(3);
stop();
$.ajax({
url: url("data/with_fries.xml"),
dataType: "xml",
success: function(resp) {
ok( $("properties", resp).length == 1, 'properties in responseXML' );
ok( $("jsconf", resp).length == 1, 'jsconf in responseXML' );
ok( $("thing", resp).length == 2, 'things in responseXML' );
start();
}
});
});
test("$.ajax - beforeSend", function() {
expect(1);
stop();
var check = false;
$.ajax({
url: url("data/name.php"),
data: {'req': true},
beforeSend: function(xml) {
check = true
},
success: function(data) {
ok( check, "check beforeSend was executed" );
start();
}
});
});
test("ajaxSetup()", function() {
expect(1);
stop();
$.ajaxSetup({
url: url("data/name.php?name=foo"),
success: function(msg){
ok( msg == 'bar', 'Check for GET' );
start();
}
});
$.ajax();
});
test("evalScripts() with no script elements", function() {
expect(2);
var data = "this is just some bogus text";
$('#foo').html(data);
ok ( true, 'before evalScripts()');
try {
$('#foo').evalScripts();
} catch(e) {
ok (false, 'exception evaluating scripts: ' + e.message);
}
ok ( true, 'after evalScripts()');
});
test("custom timeout does not set error message when timeout occurs, see #970", function() {
stop();
$.ajax({
url: "data/name.php?wait=10",
timeout: 500,
error: function(request, status) {
ok( status != null, "status shouldn't be null in error handler" );
equals( "timeout", status );
start();
}
});
});
}

Просмотреть файл

@ -1,57 +0,0 @@
#
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is
# Mozilla Foundation.
# Portions created by the Initial Developer are Copyright (C) 2007
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
#
# Alternatively, the contents of this file may be used under the terms of
# either of the GNU General Public License Version 2 or later (the "GPL"),
# or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
DEPTH = ../../../../../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
relativesrcdir = dom/tests/mochitest/ajax/jquery/src/event
include $(DEPTH)/config/autoconf.mk
DIRS = \
$(NULL)
include $(topsrcdir)/config/rules.mk
_TEST_FILES = \
event.js \
eventTest.js \
$(NULL)
libs:: $(_TEST_FILES)
$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/tests/$(relativesrcdir)

Просмотреть файл

@ -1,998 +0,0 @@
/*
* A number of helper functions used for managing events.
* Many of the ideas behind this code orignated from
* Dean Edwards' addEvent library.
*/
jQuery.event = {
// Bind an event to an element
// Original by Dean Edwards
add: function(element, type, handler, data) {
// For whatever reason, IE has trouble passing the window object
// around, causing it to be cloned in the process
if ( jQuery.browser.msie && element.setInterval != undefined )
element = window;
// Make sure that the function being executed has a unique ID
if ( !handler.guid )
handler.guid = this.guid++;
// if data is passed, bind to handler
if( data != undefined ) {
// Create temporary function pointer to original handler
var fn = handler;
// Create unique handler function, wrapped around original handler
handler = function() {
// Pass arguments and context to original handler
return fn.apply(this, arguments);
};
// Store data in unique handler
handler.data = data;
// Set the guid of unique handler to the same of original handler, so it can be removed
handler.guid = fn.guid;
}
// Init the element's event structure
if (!element.$events)
element.$events = {};
if (!element.$handle)
element.$handle = function() {
// returned undefined or false
var val;
// Handle the second event of a trigger and when
// an event is called after a page has unloaded
if ( typeof jQuery == "undefined" || jQuery.event.triggered )
return val;
val = jQuery.event.handle.apply(element, arguments);
return val;
};
// Get the current list of functions bound to this event
var handlers = element.$events[type];
// Init the event handler queue
if (!handlers) {
handlers = element.$events[type] = {};
// And bind the global event handler to the element
if (element.addEventListener)
element.addEventListener(type, element.$handle, false);
else if (element.attachEvent)
element.attachEvent("on" + type, element.$handle);
}
// Add the function to the element's handler list
handlers[handler.guid] = handler;
// Remember the function in a global list (for triggering)
if (!this.global[type])
this.global[type] = [];
// Only add the element to the global list once
if (jQuery.inArray(element, this.global[type]) == -1)
this.global[type].push( element );
},
guid: 1,
global: {},
// Detach an event or set of events from an element
remove: function(element, type, handler) {
var events = element.$events, ret, index;
if ( events ) {
// type is actually an event object here
if ( type && type.type ) {
handler = type.handler;
type = type.type;
}
if ( !type ) {
for ( type in events )
this.remove( element, type );
} else if ( events[type] ) {
// remove the given handler for the given type
if ( handler )
delete events[type][handler.guid];
// remove all handlers for the given type
else
for ( handler in element.$events[type] )
delete events[type][handler];
// remove generic event handler if no more handlers exist
for ( ret in events[type] ) break;
if ( !ret ) {
if (element.removeEventListener)
element.removeEventListener(type, element.$handle, false);
else if (element.detachEvent)
element.detachEvent("on" + type, element.$handle);
ret = null;
delete events[type];
// Remove element from the global event type cache
while ( this.global[type] && ( (index = jQuery.inArray(element, this.global[type])) >= 0 ) )
delete this.global[type][index];
}
}
// Remove the expando if it's no longer used
for ( ret in events ) break;
if ( !ret )
element.$handle = element.$events = null;
}
},
trigger: function(type, data, element) {
// Clone the incoming data, if any
data = jQuery.makeArray(data || []);
// Handle a global trigger
if ( !element )
jQuery.each( this.global[type] || [], function(){
jQuery.event.trigger( type, data, this );
});
// Handle triggering a single element
else {
var val, ret, fn = jQuery.isFunction( element[ type ] || null );
// Pass along a fake event
data.unshift( this.fix({ type: type, target: element }) );
// Trigger the event
if ( jQuery.isFunction(element.$handle) && (val = element.$handle.apply( element, data )) !== false )
this.triggered = true;
if ( fn && val !== false && !jQuery.nodeName(element, 'a') )
element[ type ]();
this.triggered = false;
}
},
handle: function(event) {
// returned undefined or false
var val;
// Empty object is for triggered events with no data
event = jQuery.event.fix( event || window.event || {} );
var c = this.$events && this.$events[event.type], args = [].slice.call( arguments, 1 );
args.unshift( event );
for ( var j in c ) {
// Pass in a reference to the handler function itself
// So that we can later remove it
args[0].handler = c[j];
args[0].data = c[j].data;
if ( c[j].apply( this, args ) === false ) {
event.preventDefault();
event.stopPropagation();
val = false;
}
}
// Clean up added properties in IE to prevent memory leak
if (jQuery.browser.msie)
event.target = event.preventDefault = event.stopPropagation =
event.handler = event.data = null;
return val;
},
fix: function(event) {
// store a copy of the original event object
// and clone to set read-only properties
var originalEvent = event;
event = jQuery.extend({}, originalEvent);
// add preventDefault and stopPropagation since
// they will not work on the clone
event.preventDefault = function() {
// if preventDefault exists run it on the original event
if (originalEvent.preventDefault)
return originalEvent.preventDefault();
// otherwise set the returnValue property of the original event to false (IE)
originalEvent.returnValue = false;
};
event.stopPropagation = function() {
// if stopPropagation exists run it on the original event
if (originalEvent.stopPropagation)
return originalEvent.stopPropagation();
// otherwise set the cancelBubble property of the original event to true (IE)
originalEvent.cancelBubble = true;
};
// Fix target property, if necessary
if ( !event.target && event.srcElement )
event.target = event.srcElement;
// check if target is a textnode (safari)
if (jQuery.browser.safari && event.target.nodeType == 3)
event.target = originalEvent.target.parentNode;
// Add relatedTarget, if necessary
if ( !event.relatedTarget && event.fromElement )
event.relatedTarget = event.fromElement == event.target ? event.toElement : event.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && event.clientX != null ) {
var e = document.documentElement || document.body;
event.pageX = event.clientX + e.scrollLeft;
event.pageY = event.clientY + e.scrollTop;
}
// Add which for key events
if ( !event.which && (event.charCode || event.keyCode) )
event.which = event.charCode || event.keyCode;
// Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
if ( !event.metaKey && event.ctrlKey )
event.metaKey = event.ctrlKey;
// Add which for click: 1 == left; 2 == middle; 3 == right
// Note: button is not normalized, so don't use it
if ( !event.which && event.button )
event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
return event;
}
};
jQuery.fn.extend({
/**
* Binds a handler to a particular event (like click) for each matched element.
* The event handler is passed an event object that you can use to prevent
* default behaviour. To stop both default action and event bubbling, your handler
* has to return false.
*
* In most cases, you can define your event handlers as anonymous functions
* (see first example). In cases where that is not possible, you can pass additional
* data as the second parameter (and the handler function as the third), see
* second example.
*
* Calling bind with an event type of "unload" will automatically
* use the one method instead of bind to prevent memory leaks.
*
* @example $("p").bind("click", function(){
* alert( $(this).text() );
* });
* @before <p>Hello</p>
* @result alert("Hello")
*
* @example function handler(event) {
* alert(event.data.foo);
* }
* $("p").bind("click", {foo: "bar"}, handler)
* @result alert("bar")
* @desc Pass some additional data to the event handler.
*
* @example $("form").bind("submit", function() { return false; })
* @desc Cancel a default action and prevent it from bubbling by returning false
* from your function.
*
* @example $("form").bind("submit", function(event){
* event.preventDefault();
* });
* @desc Cancel only the default action by using the preventDefault method.
*
*
* @example $("form").bind("submit", function(event){
* event.stopPropagation();
* });
* @desc Stop only an event from bubbling by using the stopPropagation method.
*
* @name bind
* @type jQuery
* @param String type An event type
* @param Object data (optional) Additional data passed to the event handler as event.data
* @param Function fn A function to bind to the event on each of the set of matched elements
* @cat Events
*/
bind: function( type, data, fn ) {
return type == "unload" ? this.one(type, data, fn) : this.each(function(){
jQuery.event.add( this, type, fn || data, fn && data );
});
},
/**
* Binds a handler to a particular event (like click) for each matched element.
* The handler is executed only once for each element. Otherwise, the same rules
* as described in bind() apply.
* The event handler is passed an event object that you can use to prevent
* default behaviour. To stop both default action and event bubbling, your handler
* has to return false.
*
* In most cases, you can define your event handlers as anonymous functions
* (see first example). In cases where that is not possible, you can pass additional
* data as the second paramter (and the handler function as the third), see
* second example.
*
* @example $("p").one("click", function(){
* alert( $(this).text() );
* });
* @before <p>Hello</p>
* @result alert("Hello")
*
* @name one
* @type jQuery
* @param String type An event type
* @param Object data (optional) Additional data passed to the event handler as event.data
* @param Function fn A function to bind to the event on each of the set of matched elements
* @cat Events
*/
one: function( type, data, fn ) {
return this.each(function(){
jQuery.event.add( this, type, function(event) {
jQuery(this).unbind(event);
return (fn || data).apply( this, arguments);
}, fn && data);
});
},
/**
* The opposite of bind, removes a bound event from each of the matched
* elements.
*
* Without any arguments, all bound events are removed.
*
* If the type is provided, all bound events of that type are removed.
*
* If the function that was passed to bind is provided as the second argument,
* only that specific event handler is removed.
*
* @example $("p").unbind()
* @before <p onclick="alert('Hello');">Hello</p>
* @result [ <p>Hello</p> ]
*
* @example $("p").unbind( "click" )
* @before <p onclick="alert('Hello');">Hello</p>
* @result [ <p>Hello</p> ]
*
* @example $("p").unbind( "click", function() { alert("Hello"); } )
* @before <p onclick="alert('Hello');">Hello</p>
* @result [ <p>Hello</p> ]
*
* @name unbind
* @type jQuery
* @param String type (optional) An event type
* @param Function fn (optional) A function to unbind from the event on each of the set of matched elements
* @cat Events
*/
unbind: function( type, fn ) {
return this.each(function(){
jQuery.event.remove( this, type, fn );
});
},
/**
* Trigger a type of event on every matched element. This will also cause
* the default action of the browser with the same name (if one exists)
* to be executed. For example, passing 'submit' to the trigger()
* function will also cause the browser to submit the form. This
* default action can be prevented by returning false from one of
* the functions bound to the event.
*
* You can also trigger custom events registered with bind.
*
* @example $("p").trigger("click")
* @before <p click="alert('hello')">Hello</p>
* @result alert('hello')
*
* @example $("p").click(function(event, a, b) {
* // when a normal click fires, a and b are undefined
* // for a trigger like below a refers too "foo" and b refers to "bar"
* }).trigger("click", ["foo", "bar"]);
* @desc Example of how to pass arbitrary data to an event
*
* @example $("p").bind("myEvent",function(event,message1,message2) {
* alert(message1 + ' ' + message2);
* });
* $("p").trigger("myEvent",["Hello","World"]);
* @result alert('Hello World') // One for each paragraph
*
* @name trigger
* @type jQuery
* @param String type An event type to trigger.
* @param Array data (optional) Additional data to pass as arguments (after the event object) to the event handler
* @cat Events
*/
trigger: function( type, data ) {
return this.each(function(){
jQuery.event.trigger( type, data, this );
});
},
/**
* Toggle between two function calls every other click.
* Whenever a matched element is clicked, the first specified function
* is fired, when clicked again, the second is fired. All subsequent
* clicks continue to rotate through the two functions.
*
* Use unbind("click") to remove.
*
* @example $("p").toggle(function(){
* $(this).addClass("selected");
* },function(){
* $(this).removeClass("selected");
* });
*
* @name toggle
* @type jQuery
* @param Function even The function to execute on every even click.
* @param Function odd The function to execute on every odd click.
* @cat Events
*/
toggle: function() {
// Save reference to arguments for access in closure
var a = arguments;
return this.click(function(e) {
// Figure out which function to execute
this.lastToggle = 0 == this.lastToggle ? 1 : 0;
// Make sure that clicks stop
e.preventDefault();
// and execute the function
return a[this.lastToggle].apply( this, [e] ) || false;
});
},
/**
* A method for simulating hovering (moving the mouse on, and off,
* an object). This is a custom method which provides an 'in' to a
* frequent task.
*
* Whenever the mouse cursor is moved over a matched
* element, the first specified function is fired. Whenever the mouse
* moves off of the element, the second specified function fires.
* Additionally, checks are in place to see if the mouse is still within
* the specified element itself (for example, an image inside of a div),
* and if it is, it will continue to 'hover', and not move out
* (a common error in using a mouseout event handler).
*
* @example $("p").hover(function(){
* $(this).addClass("hover");
* },function(){
* $(this).removeClass("hover");
* });
*
* @name hover
* @type jQuery
* @param Function over The function to fire whenever the mouse is moved over a matched element.
* @param Function out The function to fire whenever the mouse is moved off of a matched element.
* @cat Events
*/
hover: function(f,g) {
// A private function for handling mouse 'hovering'
function handleHover(e) {
// Check if mouse(over|out) are still within the same parent element
var p = e.relatedTarget;
// Traverse up the tree
while ( p && p != this ) try { p = p.parentNode } catch(e) { p = this; };
// If we actually just moused on to a sub-element, ignore it
if ( p == this ) return false;
// Execute the right function
return (e.type == "mouseover" ? f : g).apply(this, [e]);
}
// Bind the function to the two event listeners
return this.mouseover(handleHover).mouseout(handleHover);
},
/**
* Bind a function to be executed whenever the DOM is ready to be
* traversed and manipulated. This is probably the most important
* function included in the event module, as it can greatly improve
* the response times of your web applications.
*
* In a nutshell, this is a solid replacement for using window.onload,
* and attaching a function to that. By using this method, your bound function
* will be called the instant the DOM is ready to be read and manipulated,
* which is when what 99.99% of all JavaScript code needs to run.
*
* There is one argument passed to the ready event handler: A reference to
* the jQuery function. You can name that argument whatever you like, and
* can therefore stick with the $ alias without risk of naming collisions.
*
* Please ensure you have no code in your &lt;body&gt; onload event handler,
* otherwise $(document).ready() may not fire.
*
* You can have as many $(document).ready events on your page as you like.
* The functions are then executed in the order they were added.
*
* @example $(document).ready(function(){ Your code here... });
*
* @example jQuery(function($) {
* // Your code using failsafe $ alias here...
* });
* @desc Uses both the [[Core#.24.28_fn_.29|shortcut]] for $(document).ready() and the argument
* to write failsafe jQuery code using the $ alias, without relying on the
* global alias.
*
* @name ready
* @type jQuery
* @param Function fn The function to be executed when the DOM is ready.
* @cat Events
* @see $.noConflict()
* @see $(Function)
*/
ready: function(f) {
// If the DOM is already ready
if ( jQuery.isReady )
// Execute the function immediately
f.apply( document, [jQuery] );
// Otherwise, remember the function for later
else {
// Add the function to the wait list
jQuery.readyList.push( function() { return f.apply(this, [jQuery]) } );
}
return this;
}
});
jQuery.extend({
/*
* All the code that makes DOM Ready work nicely.
*/
isReady: false,
readyList: [],
// Handle when the DOM is ready
ready: function() {
// Make sure that the DOM is not already loaded
if ( !jQuery.isReady ) {
// Remember that the DOM is ready
jQuery.isReady = true;
// If there are functions bound, to execute
if ( jQuery.readyList ) {
// Execute all of them
jQuery.each( jQuery.readyList, function(){
this.apply( document );
});
// Reset the list of functions
jQuery.readyList = null;
}
// Remove event listener to avoid memory leak
if ( jQuery.browser.mozilla || jQuery.browser.opera )
document.removeEventListener( "DOMContentLoaded", jQuery.ready, false );
// Remove script element used by IE hack
if( !window.frames.length ) // don't remove if frames are present (#1187)
jQuery(window).load(function(){ jQuery("#__ie_init").remove(); });
}
}
});
new function(){
/**
* Bind a function to the scroll event of each matched element.
*
* @example $("p").scroll( function() { alert("Hello"); } );
* @before <p>Hello</p>
* @result <p onscroll="alert('Hello');">Hello</p>
*
* @name scroll
* @type jQuery
* @param Function fn A function to bind to the scroll event on each of the matched elements.
* @cat Events
*/
/**
* Bind a function to the submit event of each matched element.
*
* @example $("#myform").submit( function() {
* return $("input", this).val().length > 0;
* } );
* @before <form id="myform"><input /></form>
* @desc Prevents the form submission when the input has no value entered.
*
* @name submit
* @type jQuery
* @param Function fn A function to bind to the submit event on each of the matched elements.
* @cat Events
*/
/**
* Trigger the submit event of each matched element. This causes all of the functions
* that have been bound to that submit event to be executed, and calls the browser's
* default submit action on the matching element(s). This default action can be prevented
* by returning false from one of the functions bound to the submit event.
*
* Note: This does not execute the submit method of the form element! If you need to
* submit the form via code, you have to use the DOM method, eg. $("form")[0].submit();
*
* @example $("form").submit();
* @desc Triggers all submit events registered to the matched form(s), and submits them.
*
* @name submit
* @type jQuery
* @cat Events
*/
/**
* Bind a function to the focus event of each matched element.
*
* @example $("p").focus( function() { alert("Hello"); } );
* @before <p>Hello</p>
* @result <p onfocus="alert('Hello');">Hello</p>
*
* @name focus
* @type jQuery
* @param Function fn A function to bind to the focus event on each of the matched elements.
* @cat Events
*/
/**
* Trigger the focus event of each matched element. This causes all of the functions
* that have been bound to thet focus event to be executed.
*
* Note: This does not execute the focus method of the underlying elements! If you need to
* focus an element via code, you have to use the DOM method, eg. $("#myinput")[0].focus();
*
* @example $("p").focus();
* @before <p onfocus="alert('Hello');">Hello</p>
* @result alert('Hello');
*
* @name focus
* @type jQuery
* @cat Events
*/
/**
* Bind a function to the keydown event of each matched element.
*
* @example $("p").keydown( function() { alert("Hello"); } );
* @before <p>Hello</p>
* @result <p onkeydown="alert('Hello');">Hello</p>
*
* @name keydown
* @type jQuery
* @param Function fn A function to bind to the keydown event on each of the matched elements.
* @cat Events
*/
/**
* Bind a function to the dblclick event of each matched element.
*
* @example $("p").dblclick( function() { alert("Hello"); } );
* @before <p>Hello</p>
* @result <p ondblclick="alert('Hello');">Hello</p>
*
* @name dblclick
* @type jQuery
* @param Function fn A function to bind to the dblclick event on each of the matched elements.
* @cat Events
*/
/**
* Bind a function to the keypress event of each matched element.
*
* @example $("p").keypress( function() { alert("Hello"); } );
* @before <p>Hello</p>
* @result <p onkeypress="alert('Hello');">Hello</p>
*
* @name keypress
* @type jQuery
* @param Function fn A function to bind to the keypress event on each of the matched elements.
* @cat Events
*/
/**
* Bind a function to the error event of each matched element.
*
* @example $("p").error( function() { alert("Hello"); } );
* @before <p>Hello</p>
* @result <p onerror="alert('Hello');">Hello</p>
*
* @name error
* @type jQuery
* @param Function fn A function to bind to the error event on each of the matched elements.
* @cat Events
*/
/**
* Bind a function to the blur event of each matched element.
*
* @example $("p").blur( function() { alert("Hello"); } );
* @before <p>Hello</p>
* @result <p onblur="alert('Hello');">Hello</p>
*
* @name blur
* @type jQuery
* @param Function fn A function to bind to the blur event on each of the matched elements.
* @cat Events
*/
/**
* Trigger the blur event of each matched element. This causes all of the functions
* that have been bound to that blur event to be executed, and calls the browser's
* default blur action on the matching element(s). This default action can be prevented
* by returning false from one of the functions bound to the blur event.
*
* Note: This does not execute the blur method of the underlying elements! If you need to
* blur an element via code, you have to use the DOM method, eg. $("#myinput")[0].blur();
*
* @example $("p").blur();
* @before <p onblur="alert('Hello');">Hello</p>
* @result alert('Hello');
*
* @name blur
* @type jQuery
* @cat Events
*/
/**
* Bind a function to the load event of each matched element.
*
* @example $("p").load( function() { alert("Hello"); } );
* @before <p>Hello</p>
* @result <p onload="alert('Hello');">Hello</p>
*
* @name load
* @type jQuery
* @param Function fn A function to bind to the load event on each of the matched elements.
* @cat Events
*/
/**
* Bind a function to the select event of each matched element.
*
* @example $("p").select( function() { alert("Hello"); } );
* @before <p>Hello</p>
* @result <p onselect="alert('Hello');">Hello</p>
*
* @name select
* @type jQuery
* @param Function fn A function to bind to the select event on each of the matched elements.
* @cat Events
*/
/**
* Trigger the select event of each matched element. This causes all of the functions
* that have been bound to that select event to be executed, and calls the browser's
* default select action on the matching element(s). This default action can be prevented
* by returning false from one of the functions bound to the select event.
*
* @example $("p").select();
* @before <p onselect="alert('Hello');">Hello</p>
* @result alert('Hello');
*
* @name select
* @type jQuery
* @cat Events
*/
/**
* Bind a function to the mouseup event of each matched element.
*
* @example $("p").mouseup( function() { alert("Hello"); } );
* @before <p>Hello</p>
* @result <p onmouseup="alert('Hello');">Hello</p>
*
* @name mouseup
* @type jQuery
* @param Function fn A function to bind to the mouseup event on each of the matched elements.
* @cat Events
*/
/**
* Bind a function to the unload event of each matched element.
*
* @example $("p").unload( function() { alert("Hello"); } );
* @before <p>Hello</p>
* @result <p onunload="alert('Hello');">Hello</p>
*
* @name unload
* @type jQuery
* @param Function fn A function to bind to the unload event on each of the matched elements.
* @cat Events
*/
/**
* Bind a function to the change event of each matched element.
*
* @example $("p").change( function() { alert("Hello"); } );
* @before <p>Hello</p>
* @result <p onchange="alert('Hello');">Hello</p>
*
* @name change
* @type jQuery
* @param Function fn A function to bind to the change event on each of the matched elements.
* @cat Events
*/
/**
* Bind a function to the mouseout event of each matched element.
*
* @example $("p").mouseout( function() { alert("Hello"); } );
* @before <p>Hello</p>
* @result <p onmouseout="alert('Hello');">Hello</p>
*
* @name mouseout
* @type jQuery
* @param Function fn A function to bind to the mouseout event on each of the matched elements.
* @cat Events
*/
/**
* Bind a function to the keyup event of each matched element.
*
* @example $("p").keyup( function() { alert("Hello"); } );
* @before <p>Hello</p>
* @result <p onkeyup="alert('Hello');">Hello</p>
*
* @name keyup
* @type jQuery
* @param Function fn A function to bind to the keyup event on each of the matched elements.
* @cat Events
*/
/**
* Bind a function to the click event of each matched element.
*
* @example $("p").click( function() { alert("Hello"); } );
* @before <p>Hello</p>
* @result <p onclick="alert('Hello');">Hello</p>
*
* @name click
* @type jQuery
* @param Function fn A function to bind to the click event on each of the matched elements.
* @cat Events
*/
/**
* Trigger the click event of each matched element. This causes all of the functions
* that have been bound to thet click event to be executed.
*
* @example $("p").click();
* @before <p onclick="alert('Hello');">Hello</p>
* @result alert('Hello');
*
* @name click
* @type jQuery
* @cat Events
*/
/**
* Bind a function to the resize event of each matched element.
*
* @example $("p").resize( function() { alert("Hello"); } );
* @before <p>Hello</p>
* @result <p onresize="alert('Hello');">Hello</p>
*
* @name resize
* @type jQuery
* @param Function fn A function to bind to the resize event on each of the matched elements.
* @cat Events
*/
/**
* Bind a function to the mousemove event of each matched element.
*
* @example $("p").mousemove( function() { alert("Hello"); } );
* @before <p>Hello</p>
* @result <p onmousemove="alert('Hello');">Hello</p>
*
* @name mousemove
* @type jQuery
* @param Function fn A function to bind to the mousemove event on each of the matched elements.
* @cat Events
*/
/**
* Bind a function to the mousedown event of each matched element.
*
* @example $("p").mousedown( function() { alert("Hello"); } );
* @before <p>Hello</p>
* @result <p onmousedown="alert('Hello');">Hello</p>
*
* @name mousedown
* @type jQuery
* @param Function fn A function to bind to the mousedown event on each of the matched elements.
* @cat Events
*/
/**
* Bind a function to the mouseover event of each matched element.
*
* @example $("p").mouseover( function() { alert("Hello"); } );
* @before <p>Hello</p>
* @result <p onmouseover="alert('Hello');">Hello</p>
*
* @name mouseover
* @type jQuery
* @param Function fn A function to bind to the mousedown event on each of the matched elements.
* @cat Events
*/
jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
"mousedown,mouseup,mousemove,mouseover,mouseout,change,select," +
"submit,keydown,keypress,keyup,error").split(","), function(i,o){
// Handle event binding
jQuery.fn[o] = function(f){
return f ? this.bind(o, f) : this.trigger(o);
};
});
// If Mozilla is used
if ( jQuery.browser.mozilla || jQuery.browser.opera )
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", jQuery.ready, false );
// If IE is used, use the excellent hack by Matthias Miller
// http://www.outofhanwell.com/blog/index.php?title=the_window_onload_problem_revisited
else if ( jQuery.browser.msie ) {
// Only works if you document.write() it
document.write("<scr" + "ipt id=__ie_init defer=true " +
"src=//:><\/script>");
// Use the defer script hack
var script = document.getElementById("__ie_init");
// script does not exist if jQuery is loaded dynamically
if ( script )
script.onreadystatechange = function() {
if ( this.readyState != "complete" ) return;
jQuery.ready();
};
// Clear from memory
script = null;
// If Safari is used
} else if ( jQuery.browser.safari )
// Continually check to see if the document.readyState is valid
jQuery.safariTimer = setInterval(function(){
// loaded and complete are both valid states
if ( document.readyState == "loaded" ||
document.readyState == "complete" ) {
// If either one are found, remove the timer
clearInterval( jQuery.safariTimer );
jQuery.safariTimer = null;
// and execute any waiting functions
jQuery.ready();
}
}, 10);
// A fallback to window.onload, that will always work
jQuery.event.add( window, "load", jQuery.ready );
};
// Clean up after IE to avoid memory leaks
if (jQuery.browser.msie)
jQuery(window).one("unload", function() {
var global = jQuery.event.global;
for ( var type in global ) {
var els = global[type], i = els.length;
if ( i && type != 'unload' )
do
els[i-1] && jQuery.event.remove(els[i-1], type);
while (--i);
}
});

Просмотреть файл

@ -1,126 +0,0 @@
module("event");
test("bind()", function() {
expect(12);
var handler = function(event) {
ok( event.data, "bind() with data, check passed data exists" );
ok( event.data.foo == "bar", "bind() with data, Check value of passed data" );
};
$("#firstp").bind("click", {foo: "bar"}, handler).click().unbind("click", handler);
ok( !$("#firstp").get(0).$events, "Event handler unbound when using data." );
reset();
var handler = function(event, data) {
ok( event.data, "check passed data exists" );
ok( event.data.foo == "bar", "Check value of passed data" );
ok( data, "Check trigger data" );
ok( data.bar == "foo", "Check value of trigger data" );
};
$("#firstp").bind("click", {foo: "bar"}, handler).trigger("click", [{bar: "foo"}]).unbind(handler);
reset();
var handler = function(event) {
ok ( !event.data, "Check that no data is added to the event object" );
};
$("#firstp").bind("click", handler).trigger("click");
// events don't work with iframes, see #939
var tmp = document.createElement('iframe');
document.body.appendChild( tmp );
var doc = tmp.contentWindow.document;
doc.open();
doc.write("<html><body><input type='text'/></body></html>");
doc.close();
var input = doc.getElementsByTagName("input")[0];
$(input).bind("click",function() {
ok( true, "Binding to element inside iframe" );
});
triggerEvent( input, "click" );
document.body.removeChild( tmp );
var counter = 0;
function selectOnChange(event) {
equals( event.data, counter++, "Event.data is not a global event object" );
};
$("select").each(function(i){
$(this).bind('change', i, selectOnChange);
}).trigger('change');
});
test("click()", function() {
expect(3);
$('<li><a href="#">Change location</a></li>').prependTo('#firstUL').find('a').bind('click', function() {
var close = $('spanx', this); // same with $(this).find('span');
ok( close.length == 0, "Context element does not exist, length must be zero" );
ok( !close[0], "Context element does not exist, direct access to element must return undefined" );
return false;
}).click();
$("#check1").click(function() {
ok( true, "click event handler for checkbox gets fired twice, see #815" );
}).click();
});
test("unbind(event)", function() {
expect(6);
var el = $("#firstp");
el.click(function() {
ok( true, "Fake normal bind" );
});
el.click(function(event) {
el.unbind(event);
ok( true, "Fake onebind" );
});
el.click().click();
el.click(function() { return; });
el.unbind('click');
ok( !el[0].onclick, "Handler is removed" ); // Bug #964
el.click(function() { return; });
el.unbind('change',function(){ return; });
for (var ret in el[0].$events['click']) break;
ok( ret, "Extra handlers weren't accidentally removed." );
el.unbind('click');
ok( !el[0].$events, "Removed the events expando after all handlers are unbound." );
});
test("trigger(event, [data]", function() {
expect(3);
var handler = function(event, a, b, c) {
ok( a == 1, "check passed data" );
ok( b == "2", "check passed data" );
ok( c == "abc", "check passed data" );
};
$("#firstp").bind("click", handler).trigger("click", [1, "2", "abc"]);
});
test("toggle(Function, Function)", function() {
expect(4);
var count = 0,
fn1 = function(e) { count++; },
fn2 = function(e) { count--; },
preventDefault = function(e) { e.preventDefault() },
link = $('#mark');
link.click(preventDefault).click().toggle(fn1, fn2).click().click().click().click().click();
ok( count == 1, "Check for toggle(fn, fn)" );
var first = 0;
$("#simon1").one("click", function() {
ok( true, "Execute event only once" );
$(this).toggle(function() {
ok( first++ == 0, "toggle(Function,Function) assigned from within one('xxx'), see #1054" );
}, function() {
ok( first == 1, "toggle(Function,Function) assigned from within one('xxx'), see #1054" );
});
return false;
}).click().click().click();
});

Просмотреть файл

@ -1,57 +0,0 @@
#
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is
# Mozilla Foundation.
# Portions created by the Initial Developer are Copyright (C) 2007
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
#
# Alternatively, the contents of this file may be used under the terms of
# either of the GNU General Public License Version 2 or later (the "GPL"),
# or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
DEPTH = ../../../../../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
relativesrcdir = dom/tests/mochitest/ajax/jquery/src/fx
include $(DEPTH)/config/autoconf.mk
DIRS = \
$(NULL)
include $(topsrcdir)/config/rules.mk
_TEST_FILES = \
fx.js \
fxTest.js \
$(NULL)
libs:: $(_TEST_FILES)
$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/tests/$(relativesrcdir)

574
dom/tests/mochitest/ajax/jquery/src/fx/fx.js поставляемый
Просмотреть файл

@ -1,574 +0,0 @@
jQuery.fn.extend({
/**
* Displays each of the set of matched elements if they are hidden.
*
* @example $("p").show()
* @before <p style="display: none">Hello</p>
* @result [ <p style="display: block">Hello</p> ]
*
* @name show
* @type jQuery
* @cat Effects
*/
/**
* Show all matched elements using a graceful animation and firing an
* optional callback after completion.
*
* The height, width, and opacity of each of the matched elements
* are changed dynamically according to the specified speed.
*
* @example $("p").show("slow");
*
* @example $("p").show("slow",function(){
* alert("Animation Done.");
* });
*
* @name show
* @type jQuery
* @param String|Number speed A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
* @param Function callback (optional) A function to be executed whenever the animation completes.
* @cat Effects
* @see hide(String|Number,Function)
*/
show: function(speed,callback){
return speed ?
this.animate({
height: "show", width: "show", opacity: "show"
}, speed, callback) :
this.filter(":hidden").each(function(){
this.style.display = this.oldblock ? this.oldblock : "";
if ( jQuery.css(this,"display") == "none" )
this.style.display = "block";
}).end();
},
/**
* Hides each of the set of matched elements if they are shown.
*
* @example $("p").hide()
* @before <p>Hello</p>
* @result [ <p style="display: none">Hello</p> ]
*
* @name hide
* @type jQuery
* @cat Effects
*/
/**
* Hide all matched elements using a graceful animation and firing an
* optional callback after completion.
*
* The height, width, and opacity of each of the matched elements
* are changed dynamically according to the specified speed.
*
* @example $("p").hide("slow");
*
* @example $("p").hide("slow",function(){
* alert("Animation Done.");
* });
*
* @name hide
* @type jQuery
* @param String|Number speed A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
* @param Function callback (optional) A function to be executed whenever the animation completes.
* @cat Effects
* @see show(String|Number,Function)
*/
hide: function(speed,callback){
return speed ?
this.animate({
height: "hide", width: "hide", opacity: "hide"
}, speed, callback) :
this.filter(":visible").each(function(){
this.oldblock = this.oldblock || jQuery.css(this,"display");
if ( this.oldblock == "none" )
this.oldblock = "block";
this.style.display = "none";
}).end();
},
// Save the old toggle function
_toggle: jQuery.fn.toggle,
/**
* Toggles each of the set of matched elements. If they are shown,
* toggle makes them hidden. If they are hidden, toggle
* makes them shown.
*
* @example $("p").toggle()
* @before <p>Hello</p><p style="display: none">Hello Again</p>
* @result [ <p style="display: none">Hello</p>, <p style="display: block">Hello Again</p> ]
*
* @name toggle
* @type jQuery
* @cat Effects
*/
toggle: function( fn, fn2 ){
return jQuery.isFunction(fn) && jQuery.isFunction(fn2) ?
this._toggle( fn, fn2 ) :
fn ?
this.animate({
height: "toggle", width: "toggle", opacity: "toggle"
}, fn, fn2) :
this.each(function(){
jQuery(this)[ jQuery(this).is(":hidden") ? "show" : "hide" ]();
});
},
/**
* Reveal all matched elements by adjusting their height and firing an
* optional callback after completion.
*
* Only the height is adjusted for this animation, causing all matched
* elements to be revealed in a "sliding" manner.
*
* @example $("p").slideDown("slow");
*
* @example $("p").slideDown("slow",function(){
* alert("Animation Done.");
* });
*
* @name slideDown
* @type jQuery
* @param String|Number speed (optional) A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
* @param Function callback (optional) A function to be executed whenever the animation completes.
* @cat Effects
* @see slideUp(String|Number,Function)
* @see slideToggle(String|Number,Function)
*/
slideDown: function(speed,callback){
return this.animate({height: "show"}, speed, callback);
},
/**
* Hide all matched elements by adjusting their height and firing an
* optional callback after completion.
*
* Only the height is adjusted for this animation, causing all matched
* elements to be hidden in a "sliding" manner.
*
* @example $("p").slideUp("slow");
*
* @example $("p").slideUp("slow",function(){
* alert("Animation Done.");
* });
*
* @name slideUp
* @type jQuery
* @param String|Number speed (optional) A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
* @param Function callback (optional) A function to be executed whenever the animation completes.
* @cat Effects
* @see slideDown(String|Number,Function)
* @see slideToggle(String|Number,Function)
*/
slideUp: function(speed,callback){
return this.animate({height: "hide"}, speed, callback);
},
/**
* Toggle the visibility of all matched elements by adjusting their height and firing an
* optional callback after completion.
*
* Only the height is adjusted for this animation, causing all matched
* elements to be hidden in a "sliding" manner.
*
* @example $("p").slideToggle("slow");
*
* @example $("p").slideToggle("slow",function(){
* alert("Animation Done.");
* });
*
* @name slideToggle
* @type jQuery
* @param String|Number speed (optional) A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
* @param Function callback (optional) A function to be executed whenever the animation completes.
* @cat Effects
* @see slideDown(String|Number,Function)
* @see slideUp(String|Number,Function)
*/
slideToggle: function(speed, callback){
return this.animate({height: "toggle"}, speed, callback);
},
/**
* Fade in all matched elements by adjusting their opacity and firing an
* optional callback after completion.
*
* Only the opacity is adjusted for this animation, meaning that
* all of the matched elements should already have some form of height
* and width associated with them.
*
* @example $("p").fadeIn("slow");
*
* @example $("p").fadeIn("slow",function(){
* alert("Animation Done.");
* });
*
* @name fadeIn
* @type jQuery
* @param String|Number speed (optional) A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
* @param Function callback (optional) A function to be executed whenever the animation completes.
* @cat Effects
* @see fadeOut(String|Number,Function)
* @see fadeTo(String|Number,Number,Function)
*/
fadeIn: function(speed, callback){
return this.animate({opacity: "show"}, speed, callback);
},
/**
* Fade out all matched elements by adjusting their opacity and firing an
* optional callback after completion.
*
* Only the opacity is adjusted for this animation, meaning that
* all of the matched elements should already have some form of height
* and width associated with them.
*
* @example $("p").fadeOut("slow");
*
* @example $("p").fadeOut("slow",function(){
* alert("Animation Done.");
* });
*
* @name fadeOut
* @type jQuery
* @param String|Number speed (optional) A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
* @param Function callback (optional) A function to be executed whenever the animation completes.
* @cat Effects
* @see fadeIn(String|Number,Function)
* @see fadeTo(String|Number,Number,Function)
*/
fadeOut: function(speed, callback){
return this.animate({opacity: "hide"}, speed, callback);
},
/**
* Fade the opacity of all matched elements to a specified opacity and firing an
* optional callback after completion.
*
* Only the opacity is adjusted for this animation, meaning that
* all of the matched elements should already have some form of height
* and width associated with them.
*
* @example $("p").fadeTo("slow", 0.5);
*
* @example $("p").fadeTo("slow", 0.5, function(){
* alert("Animation Done.");
* });
*
* @name fadeTo
* @type jQuery
* @param String|Number speed A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
* @param Number opacity The opacity to fade to (a number from 0 to 1).
* @param Function callback (optional) A function to be executed whenever the animation completes.
* @cat Effects
* @see fadeIn(String|Number,Function)
* @see fadeOut(String|Number,Function)
*/
fadeTo: function(speed,to,callback){
return this.animate({opacity: to}, speed, callback);
},
/**
* A function for making your own, custom animations. The key aspect of
* this function is the object of style properties that will be animated,
* and to what end. Each key within the object represents a style property
* that will also be animated (for example: "height", "top", or "opacity").
*
* Note that properties should be specified using camel case
* eg. marginLeft instead of margin-left.
*
* The value associated with the key represents to what end the property
* will be animated. If a number is provided as the value, then the style
* property will be transitioned from its current state to that new number.
* Otherwise if the string "hide", "show", or "toggle" is provided, a default
* animation will be constructed for that property.
*
* @example $("p").animate({
* height: 'toggle', opacity: 'toggle'
* }, "slow");
*
* @example $("p").animate({
* left: 50, opacity: 'show'
* }, 500);
*
* @example $("p").animate({
* opacity: 'show'
* }, "slow", "easein");
* @desc An example of using an 'easing' function to provide a different style of animation. This will only work if you have a plugin that provides this easing function (Only "swing" and "linear" are provided by default, with jQuery).
*
* @name animate
* @type jQuery
* @param Hash params A set of style attributes that you wish to animate, and to what end.
* @param String|Number speed (optional) A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
* @param String easing (optional) The name of the easing effect that you want to use (e.g. "swing" or "linear"). Defaults to "swing".
* @param Function callback (optional) A function to be executed whenever the animation completes.
* @cat Effects
*/
animate: function( prop, speed, easing, callback ) {
return this.queue(function(){
var hidden = jQuery(this).is(":hidden"),
opt = jQuery.speed(speed, easing, callback),
self = this;
for ( var p in prop )
if ( prop[p] == "hide" && hidden || prop[p] == "show" && !hidden )
return jQuery.isFunction(opt.complete) && opt.complete.apply(this);
this.curAnim = jQuery.extend({}, prop);
jQuery.each( prop, function(name, val){
var e = new jQuery.fx( self, opt, name );
if ( val.constructor == Number )
e.custom( e.cur(), val );
else
e[ val == "toggle" ? hidden ? "show" : "hide" : val ]( prop );
});
});
},
/**
*
* @private
*/
queue: function(type,fn){
if ( !fn ) {
fn = type;
type = "fx";
}
return this.each(function(){
if ( !this.queue )
this.queue = {};
if ( !this.queue[type] )
this.queue[type] = [];
this.queue[type].push( fn );
if ( this.queue[type].length == 1 )
fn.apply(this);
});
}
});
jQuery.extend({
speed: function(speed, easing, fn) {
var opt = speed && speed.constructor == Object ? speed : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && easing.constructor != Function && easing || (jQuery.easing.swing ? "swing" : "linear")
};
opt.duration = (opt.duration && opt.duration.constructor == Number ?
opt.duration :
{ slow: 600, fast: 200 }[opt.duration]) || 400;
// Queueing
opt.old = opt.complete;
opt.complete = function(){
jQuery.dequeue(this, "fx");
if ( jQuery.isFunction( opt.old ) )
opt.old.apply( this );
};
return opt;
},
easing: {
linear: function( p, n, firstNum, diff ) {
return firstNum + diff * p;
},
swing: function( p, n, firstNum, diff ) {
return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum;
}
},
queue: {},
dequeue: function(elem,type){
type = type || "fx";
if ( elem.queue && elem.queue[type] ) {
// Remove self
elem.queue[type].shift();
// Get next function
var f = elem.queue[type][0];
if ( f ) f.apply( elem );
}
},
timers: [],
/*
* I originally wrote fx() as a clone of moo.fx and in the process
* of making it small in size the code became illegible to sane
* people. You've been warned.
*/
fx: function( elem, options, prop ){
var z = this;
// The styles
var y = elem.style;
if ( prop == "height" || prop == "width" ) {
// Store display property
var oldDisplay = jQuery.css(elem, "display");
// Make sure that nothing sneaks out
var oldOverflow = y.overflow;
y.overflow = "hidden";
}
// Simple function for setting a style value
z.a = function(){
if ( options.step )
options.step.apply( elem, [ z.now ] );
if ( prop == "opacity" )
jQuery.attr(y, "opacity", z.now); // Let attr handle opacity
else {
y[prop] = parseInt(z.now) + "px";
y.display = "block"; // Set display property to block for animation
}
};
// Figure out the maximum number to run to
z.max = function(){
return parseFloat( jQuery.css(elem,prop) );
};
// Get the current size
z.cur = function(){
var r = parseFloat( jQuery.curCSS(elem, prop) );
return r && r > -10000 ? r : z.max();
};
// Start an animation from one number to another
z.custom = function(from,to){
z.startTime = (new Date()).getTime();
z.now = from;
z.a();
jQuery.timers.push(function(){
return z.step(from, to);
});
if ( jQuery.timers.length == 1 ) {
var timer = setInterval(function(){
var timers = jQuery.timers;
for ( var i = 0; i < timers.length; i++ )
if ( !timers[i]() )
timers.splice(i--, 1);
if ( !timers.length )
clearInterval( timer );
}, 13);
}
};
// Simple 'show' function
z.show = function(){
if ( !elem.orig ) elem.orig = {};
// Remember where we started, so that we can go back to it later
elem.orig[prop] = jQuery.attr( elem.style, prop );
options.show = true;
// Begin the animation
z.custom(0, this.cur());
// Make sure that we start at a small width/height to avoid any
// flash of content
if ( prop != "opacity" )
y[prop] = "1px";
// Start by showing the element
jQuery(elem).show();
};
// Simple 'hide' function
z.hide = function(){
if ( !elem.orig ) elem.orig = {};
// Remember where we started, so that we can go back to it later
elem.orig[prop] = jQuery.attr( elem.style, prop );
options.hide = true;
// Begin the animation
z.custom(this.cur(), 0);
};
// Each step of an animation
z.step = function(firstNum, lastNum){
var t = (new Date()).getTime();
if (t > options.duration + z.startTime) {
z.now = lastNum;
z.a();
if (elem.curAnim) elem.curAnim[ prop ] = true;
var done = true;
for ( var i in elem.curAnim )
if ( elem.curAnim[i] !== true )
done = false;
if ( done ) {
if ( oldDisplay != null ) {
// Reset the overflow
y.overflow = oldOverflow;
// Reset the display
y.display = oldDisplay;
if ( jQuery.css(elem, "display") == "none" )
y.display = "block";
}
// Hide the element if the "hide" operation was done
if ( options.hide )
y.display = "none";
// Reset the properties, if the item has been hidden or shown
if ( options.hide || options.show )
for ( var p in elem.curAnim )
jQuery.attr(y, p, elem.orig[p]);
}
// If a callback was provided, execute it
if ( done && jQuery.isFunction( options.complete ) )
// Execute the complete function
options.complete.apply( elem );
return false;
} else {
var n = t - this.startTime;
// Figure out where in the animation we are and set the number
var p = n / options.duration;
// Perform the easing function, defaults to swing
z.now = jQuery.easing[options.easing](p, n, firstNum, (lastNum-firstNum), options.duration);
// Perform the next step of the animation
z.a();
}
return true;
};
}
});

Просмотреть файл

@ -1,22 +0,0 @@
module("fx");
test("animate(Hash, Object, Function)", function() {
expect(1);
stop();
var hash = {opacity: 'show'};
var hashCopy = $.extend({}, hash);
$('#foo').animate(hash, 0, function() {
ok( hash.opacity == hashCopy.opacity, 'Check if animate changed the hash parameter' );
start();
});
});
test("toggle()", function() {
expect(3);
var x = $("#foo");
ok( x.is(":visible") );
x.toggle();
ok( x.is(":hidden") );
x.toggle();
ok( x.is(":visible") );
});

Просмотреть файл

@ -1,2 +0,0 @@
// prevent execution of jQuery if included more than once
if(typeof window.jQuery == "undefined") {

Просмотреть файл

@ -1,57 +0,0 @@
#
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is
# Mozilla Foundation.
# Portions created by the Initial Developer are Copyright (C) 2007
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
#
# Alternatively, the contents of this file may be used under the terms of
# either of the GNU General Public License Version 2 or later (the "GPL"),
# or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
DEPTH = ../../../../../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
relativesrcdir = dom/tests/mochitest/ajax/jquery/src/jquery
include $(DEPTH)/config/autoconf.mk
DIRS = \
$(NULL)
include $(topsrcdir)/config/rules.mk
_TEST_FILES = \
coreTest.js \
jquery.js \
$(NULL)
libs:: $(_TEST_FILES)
$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/tests/$(relativesrcdir)

Просмотреть файл

@ -1,893 +0,0 @@
module("core");
test("Basic requirements", function() {
expect(7);
ok( Array.prototype.push, "Array.push()" );
ok( Function.prototype.apply, "Function.apply()" );
ok( document.getElementById, "getElementById" );
ok( document.getElementsByTagName, "getElementsByTagName" );
ok( RegExp, "RegExp" );
ok( jQuery, "jQuery" );
ok( $, "$()" );
});
test("$()", function() {
expect(2);
var main = $("#main");
isSet( $("div p", main).get(), q("sndp", "en", "sap"), "Basic selector with jQuery object as context" );
// make sure this is handled
$('<p>\r\n</p>');
ok( true, "Check for \\r and \\n in jQuery()" );
/*
var pass = true;
try {
var f = document.getElementById("iframe").contentDocument;
f.open();
f.write("<html><body></body></html>");
f.close();
$("<div>Testing</div>").appendTo(f.body);
} catch(e){
pass = false;
}
ok( pass, "$('&lt;tag&gt;') needs optional document parameter to ease cross-frame DOM wrangling, see #968" );
*/
});
test("isFunction", function() {
expect(21);
// Make sure that false values return false
ok( !jQuery.isFunction(), "No Value" );
ok( !jQuery.isFunction( null ), "null Value" );
ok( !jQuery.isFunction( undefined ), "undefined Value" );
ok( !jQuery.isFunction( "" ), "Empty String Value" );
ok( !jQuery.isFunction( 0 ), "0 Value" );
// Check built-ins
// Safari uses "(Internal Function)"
ok( jQuery.isFunction(String), "String Function" );
ok( jQuery.isFunction(Array), "Array Function" );
ok( jQuery.isFunction(Object), "Object Function" );
ok( jQuery.isFunction(Function), "Function Function" );
// When stringified, this could be misinterpreted
var mystr = "function";
ok( !jQuery.isFunction(mystr), "Function String" );
// When stringified, this could be misinterpreted
var myarr = [ "function" ];
ok( !jQuery.isFunction(myarr), "Function Array" );
// When stringified, this could be misinterpreted
var myfunction = { "function": "test" };
ok( !jQuery.isFunction(myfunction), "Function Object" );
// Make sure normal functions still work
var fn = function(){};
ok( jQuery.isFunction(fn), "Normal Function" );
var obj = document.createElement("object");
// Firefox says this is a function
ok( !jQuery.isFunction(obj), "Object Element" );
// IE says this is an object
ok( jQuery.isFunction(obj.getAttribute), "getAttribute Function" );
var nodes = document.body.childNodes;
// Safari says this is a function
ok( !jQuery.isFunction(nodes), "childNodes Property" );
var first = document.body.firstChild;
// Normal elements are reported ok everywhere
ok( !jQuery.isFunction(first), "A normal DOM Element" );
var input = document.createElement("input");
input.type = "text";
document.body.appendChild( input );
// IE says this is an object
ok( jQuery.isFunction(input.focus), "A default function property" );
document.body.removeChild( input );
var a = document.createElement("a");
a.href = "some-function";
document.body.appendChild( a );
// This serializes with the word 'function' in it
ok( !jQuery.isFunction(a), "Anchor Element" );
document.body.removeChild( a );
// Recursive function calls have lengths and array-like properties
function callme(callback){
function fn(response){
callback(response);
}
ok( jQuery.isFunction(fn), "Recursive Function Call" );
fn({ some: "data" });
};
callme(function(){
callme(function(){});
});
});
test("length", function() {
expect(1);
ok( $("div").length == 2, "Get Number of Elements Found" );
});
test("size()", function() {
expect(1);
ok( $("div").size() == 2, "Get Number of Elements Found" );
});
test("get()", function() {
expect(1);
isSet( $("div").get(), q("main","foo"), "Get All Elements" );
});
test("get(Number)", function() {
expect(1);
ok( $("div").get(0) == document.getElementById("main"), "Get A Single Element" );
});
test("add(String|Element|Array)", function() {
expect(7);
isSet( $("#sndp").add("#en").add("#sap").get(), q("sndp", "en", "sap"), "Check elements from document" );
isSet( $("#sndp").add( $("#en")[0] ).add( $("#sap") ).get(), q("sndp", "en", "sap"), "Check elements from document" );
ok( $([]).add($("#form")[0].elements).length > 13, "Check elements from array" );
var x = $([]).add($("<p id='x1'>xxx</p>")).add($("<p id='x2'>xxx</p>"));
ok( x[0].id == "x1", "Check on-the-fly element1" );
ok( x[1].id == "x2", "Check on-the-fly element2" );
var x = $([]).add("<p id='x1'>xxx</p>").add("<p id='x2'>xxx</p>");
ok( x[0].id == "x1", "Check on-the-fly element1" );
ok( x[1].id == "x2", "Check on-the-fly element2" );
});
test("each(Function)", function() {
expect(1);
var div = $("div");
div.each(function(){this.foo = 'zoo';});
var pass = true;
for ( var i = 0; i < div.size(); i++ ) {
if ( div.get(i).foo != "zoo" ) pass = false;
}
ok( pass, "Execute a function, Relative" );
});
test("index(Object)", function() {
expect(8);
ok( $([window, document]).index(window) == 0, "Check for index of elements" );
ok( $([window, document]).index(document) == 1, "Check for index of elements" );
var inputElements = $('#radio1,#radio2,#check1,#check2');
ok( inputElements.index(document.getElementById('radio1')) == 0, "Check for index of elements" );
ok( inputElements.index(document.getElementById('radio2')) == 1, "Check for index of elements" );
ok( inputElements.index(document.getElementById('check1')) == 2, "Check for index of elements" );
ok( inputElements.index(document.getElementById('check2')) == 3, "Check for index of elements" );
ok( inputElements.index(window) == -1, "Check for not found index" );
ok( inputElements.index(document) == -1, "Check for not found index" );
});
test("attr(String)", function() {
expect(13);
ok( $('#text1').attr('value') == "Test", 'Check for value attribute' );
ok( $('#text1').attr('type') == "text", 'Check for type attribute' );
ok( $('#radio1').attr('type') == "radio", 'Check for type attribute' );
ok( $('#check1').attr('type') == "checkbox", 'Check for type attribute' );
ok( $('#simon1').attr('rel') == "bookmark", 'Check for rel attribute' );
ok( $('#google').attr('title') == "Google!", 'Check for title attribute' );
ok( $('#mark').attr('hreflang') == "en", 'Check for hreflang attribute' );
ok( $('#en').attr('lang') == "en", 'Check for lang attribute' );
ok( $('#simon').attr('class') == "blog link", 'Check for class attribute' );
ok( $('#name').attr('name') == "name", 'Check for name attribute' );
ok( $('#text1').attr('name') == "action", 'Check for name attribute' );
ok( $('#form').attr('action').indexOf("formaction") >= 0, 'Check for action attribute' );
$('<a id="tAnchor5"></a>').attr('href', '#5').appendTo('#main'); // using innerHTML in IE causes href attribute to be serialized to the full path
ok( $('#tAnchor5').attr('href') == "#5", 'Check for non-absolute href (an anchor)' );
});
/*if ( location.protocol != "file:" ) {
test("attr(String) in XML Files", function() {
expect(2);
stop();
$.get("data/dashboard.xml", function(xml) {
ok( $("locations", xml).attr("class") == "foo", "Check class attribute in XML document" );
ok( $("location", xml).attr("for") == "bar", "Check for attribute in XML document" );
start();
});
});
}*/
test("attr(String, Function)", function() {
expect(2);
ok( $('#text1').attr('value', function() { return this.id })[0].value == "text1", "Set value from id" );
ok( $('#text1').attr('title', function(i) { return i }).attr('title') == "0", "Set value with an index");
});
test("attr(Hash)", function() {
expect(1);
var pass = true;
$("div").attr({foo: 'baz', zoo: 'ping'}).each(function(){
if ( this.getAttribute('foo') != "baz" && this.getAttribute('zoo') != "ping" ) pass = false;
});
ok( pass, "Set Multiple Attributes" );
});
test("attr(String, Object)", function() {
expect(8);
var div = $("div");
div.attr("foo", "bar");
var pass = true;
for ( var i = 0; i < div.size(); i++ ) {
if ( div.get(i).getAttribute('foo') != "bar" ) pass = false;
}
ok( pass, "Set Attribute" );
ok( $("#foo").attr({"width": null}), "Try to set an attribute to nothing" );
$("#name").attr('name', 'something');
ok( $("#name").attr('name') == 'something', 'Set name attribute' );
$("#check2").attr('checked', true);
ok( document.getElementById('check2').checked == true, 'Set checked attribute' );
$("#check2").attr('checked', false);
ok( document.getElementById('check2').checked == false, 'Set checked attribute' );
$("#text1").attr('readonly', true);
ok( document.getElementById('text1').readOnly == true, 'Set readonly attribute' );
$("#text1").attr('readonly', false);
ok( document.getElementById('text1').readOnly == false, 'Set readonly attribute' );
$("#name").attr('maxlength', '5');
ok( document.getElementById('name').maxLength == '5', 'Set maxlength attribute' );
});
/*if ( location.protocol != "file:" ) {
test("attr(String, Object)x", function() {
expect(2);
stop();
$.get('data/dashboard.xml', function(xml) {
var titles = [];
$('tab', xml).each(function() {
titles.push($(this).attr('title'));
});
ok( titles[0] == 'Location', 'attr() in XML context: Check first title' );
ok( titles[1] == 'Users', 'attr() in XML context: Check second title' );
start();
});
});
}*/
test("css(String|Hash)", function() {
expect(19);
ok( $('#main').css("display") == 'none', 'Check for css property "display"');
ok( $('#foo').is(':visible'), 'Modifying CSS display: Assert element is visible');
$('#foo').css({display: 'none'});
ok( !$('#foo').is(':visible'), 'Modified CSS display: Assert element is hidden');
$('#foo').css({display: 'block'});
ok( $('#foo').is(':visible'), 'Modified CSS display: Assert element is visible');
$('#floatTest').css({styleFloat: 'right'});
ok( $('#floatTest').css('styleFloat') == 'right', 'Modified CSS float using "styleFloat": Assert float is right');
$('#floatTest').css({cssFloat: 'left'});
ok( $('#floatTest').css('cssFloat') == 'left', 'Modified CSS float using "cssFloat": Assert float is left');
$('#floatTest').css({'float': 'right'});
ok( $('#floatTest').css('float') == 'right', 'Modified CSS float using "float": Assert float is right');
$('#floatTest').css({'font-size': '30px'});
ok( $('#floatTest').css('font-size') == '30px', 'Modified CSS font-size: Assert font-size is 30px');
$.each("0,0.25,0.5,0.75,1".split(','), function(i, n) {
$('#foo').css({opacity: n});
ok( $('#foo').css('opacity') == parseFloat(n), "Assert opacity is " + parseFloat(n) + " as a String" );
$('#foo').css({opacity: parseFloat(n)});
ok( $('#foo').css('opacity') == parseFloat(n), "Assert opacity is " + parseFloat(n) + " as a Number" );
});
$('#foo').css({opacity: ''});
ok( $('#foo').css('opacity') == '1', "Assert opacity is 1 when set to an empty String" );
});
test("css(String, Object)", function() {
expect(18);
ok( $('#foo').is(':visible'), 'Modifying CSS display: Assert element is visible');
$('#foo').css('display', 'none');
ok( !$('#foo').is(':visible'), 'Modified CSS display: Assert element is hidden');
$('#foo').css('display', 'block');
ok( $('#foo').is(':visible'), 'Modified CSS display: Assert element is visible');
$('#floatTest').css('styleFloat', 'left');
ok( $('#floatTest').css('styleFloat') == 'left', 'Modified CSS float using "styleFloat": Assert float is left');
$('#floatTest').css('cssFloat', 'right');
ok( $('#floatTest').css('cssFloat') == 'right', 'Modified CSS float using "cssFloat": Assert float is right');
$('#floatTest').css('float', 'left');
ok( $('#floatTest').css('float') == 'left', 'Modified CSS float using "float": Assert float is left');
$('#floatTest').css('font-size', '20px');
ok( $('#floatTest').css('font-size') == '20px', 'Modified CSS font-size: Assert font-size is 20px');
$.each("0,0.25,0.5,0.75,1".split(','), function(i, n) {
$('#foo').css('opacity', n);
ok( $('#foo').css('opacity') == parseFloat(n), "Assert opacity is " + parseFloat(n) + " as a String" );
$('#foo').css('opacity', parseFloat(n));
ok( $('#foo').css('opacity') == parseFloat(n), "Assert opacity is " + parseFloat(n) + " as a Number" );
});
$('#foo').css('opacity', '');
ok( $('#foo').css('opacity') == '1', "Assert opacity is 1 when set to an empty String" );
});
test("text()", function() {
expect(1);
var expected = "This link has class=\"blog\": Simon Willison's Weblog";
ok( $('#sap').text() == expected, 'Check for merged text of more then one element.' );
});
test("wrap(String|Element)", function() {
expect(7);
var defaultText = 'Try them out:'
var result = $('#first').wrap('<div class="red"><span></span></div>').text();
ok( defaultText == result, 'Check for wrapping of on-the-fly html' );
ok( $('#first').parent().parent().is('.red'), 'Check if wrapper has class "red"' );
reset();
var defaultText = 'Try them out:'
var result = $('#first').wrap(document.getElementById('empty')).parent();
ok( result.is('ol'), 'Check for element wrapping' );
ok( result.text() == defaultText, 'Check for element wrapping' );
reset();
stop();
$('#check1').click(function() {
var checkbox = this;
ok( checkbox.checked, "Checkbox's state is erased after wrap() action, see #769" );
$(checkbox).wrap( '<div id="c1" style="display:none;"></div>' );
ok( checkbox.checked, "Checkbox's state is erased after wrap() action, see #769" );
// use a fade in to check state after this event handler has finished
setTimeout(function() {
ok( !checkbox.checked, "Checkbox's state is erased after wrap() action, see #769" );
start();
}, 100);
}).click();
});
test("append(String|Element|Array&lt;Element&gt;|jQuery)", function() {
expect(17);
var defaultText = 'Try them out:'
var result = $('#first').append('<b>buga</b>');
ok( result.text() == defaultText + 'buga', 'Check if text appending works' );
ok( $('#select3').append('<option value="appendTest">Append Test</option>').find('option:last-child').attr('value') == 'appendTest', 'Appending html options to select element');
reset();
var expected = "This link has class=\"blog\": Simon Willison's WeblogTry them out:";
$('#sap').append(document.getElementById('first'));
ok( expected == $('#sap').text(), "Check for appending of element" );
reset();
expected = "This link has class=\"blog\": Simon Willison's WeblogTry them out:Yahoo";
$('#sap').append([document.getElementById('first'), document.getElementById('yahoo')]);
ok( expected == $('#sap').text(), "Check for appending of array of elements" );
reset();
expected = "This link has class=\"blog\": Simon Willison's WeblogTry them out:Yahoo";
$('#sap').append($("#first, #yahoo"));
ok( expected == $('#sap').text(), "Check for appending of jQuery object" );
reset();
$("#sap").append( 5 );
ok( $("#sap")[0].innerHTML.match( /5$/ ), "Check for appending a number" );
reset();
$("#sap").append( " text with spaces " );
ok( $("#sap")[0].innerHTML.match(/ text with spaces $/), "Check for appending text with spaces" );
reset();
ok( $("#sap").append([]), "Check for appending an empty array." );
ok( $("#sap").append(""), "Check for appending an empty string." );
ok( $("#sap").append(document.getElementsByTagName("foo")), "Check for appending an empty nodelist." );
reset();
$("#sap").append(document.getElementById('form'));
ok( $("#sap>form").size() == 1, "Check for appending a form" ); // Bug #910
reset();
var pass = true;
try {
$( $("iframe")[0].contentWindow.document.body ).append("<div>test</div>");
} catch(e) {
pass = false;
}
ok( pass, "Test for appending a DOM node to the contents of an IFrame" );
reset();
$('<fieldset>').appendTo('#form').append('<legend id="legend">test</legend>');
t( 'Append legend', '#legend', ['legend'] );
reset();
$('#select1').append('<OPTION>Test</OPTION>');
ok( $('#select1 option:last').text() == "Test", "Appending &lt;OPTION&gt; (all caps)" );
$('#table').append('<colgroup></colgroup>');
ok( $('#table colgroup').length, "Append colgroup" );
$('#table colgroup').append('<col>');
ok( $('#table colgroup col').length, "Append col" );
reset();
$('form:last')
.append('<select id="appendSelect1"></select>')
.append('<select id="appendSelect2"><option>Test</option></select>');
t( "Append Select", "#appendSelect1, #appendSelect2", ["appendSelect1", "appendSelect2"] );
});
test("appendTo(String|Element|Array&lt;Element&gt;|jQuery)", function() {
expect(6);
var defaultText = 'Try them out:'
$('<b>buga</b>').appendTo('#first');
ok( $("#first").text() == defaultText + 'buga', 'Check if text appending works' );
ok( $('<option value="appendTest">Append Test</option>').appendTo('#select3').parent().find('option:last-child').attr('value') == 'appendTest', 'Appending html options to select element');
reset();
var expected = "This link has class=\"blog\": Simon Willison's WeblogTry them out:";
$(document.getElementById('first')).appendTo('#sap');
ok( expected == $('#sap').text(), "Check for appending of element" );
reset();
expected = "This link has class=\"blog\": Simon Willison's WeblogTry them out:Yahoo";
$([document.getElementById('first'), document.getElementById('yahoo')]).appendTo('#sap');
ok( expected == $('#sap').text(), "Check for appending of array of elements" );
reset();
expected = "This link has class=\"blog\": Simon Willison's WeblogTry them out:Yahoo";
$("#first, #yahoo").appendTo('#sap');
ok( expected == $('#sap').text(), "Check for appending of jQuery object" );
reset();
$('#select1').appendTo('#foo');
t( 'Append select', '#foo select', ['select1'] );
});
test("prepend(String|Element|Array&lt;Element&gt;|jQuery)", function() {
expect(5);
var defaultText = 'Try them out:'
var result = $('#first').prepend('<b>buga</b>');
ok( result.text() == 'buga' + defaultText, 'Check if text prepending works' );
ok( $('#select3').prepend('<option value="prependTest">Prepend Test</option>').find('option:first-child').attr('value') == 'prependTest', 'Prepending html options to select element');
reset();
var expected = "Try them out:This link has class=\"blog\": Simon Willison's Weblog";
$('#sap').prepend(document.getElementById('first'));
ok( expected == $('#sap').text(), "Check for prepending of element" );
reset();
expected = "Try them out:YahooThis link has class=\"blog\": Simon Willison's Weblog";
$('#sap').prepend([document.getElementById('first'), document.getElementById('yahoo')]);
ok( expected == $('#sap').text(), "Check for prepending of array of elements" );
reset();
expected = "Try them out:YahooThis link has class=\"blog\": Simon Willison's Weblog";
$('#sap').prepend($("#first, #yahoo"));
ok( expected == $('#sap').text(), "Check for prepending of jQuery object" );
});
test("prependTo(String|Element|Array&lt;Element&gt;|jQuery)", function() {
expect(6);
var defaultText = 'Try them out:'
$('<b>buga</b>').prependTo('#first');
ok( $('#first').text() == 'buga' + defaultText, 'Check if text prepending works' );
ok( $('<option value="prependTest">Prepend Test</option>').prependTo('#select3').parent().find('option:first-child').attr('value') == 'prependTest', 'Prepending html options to select element');
reset();
var expected = "Try them out:This link has class=\"blog\": Simon Willison's Weblog";
$(document.getElementById('first')).prependTo('#sap');
ok( expected == $('#sap').text(), "Check for prepending of element" );
reset();
expected = "Try them out:YahooThis link has class=\"blog\": Simon Willison's Weblog";
$([document.getElementById('yahoo'), document.getElementById('first')]).prependTo('#sap');
ok( expected == $('#sap').text(), "Check for prepending of array of elements" );
reset();
expected = "Try them out:YahooThis link has class=\"blog\": Simon Willison's Weblog";
$("#yahoo, #first").prependTo('#sap');
ok( expected == $('#sap').text(), "Check for prepending of jQuery object" );
reset();
$('<select id="prependSelect1"></select>').prependTo('form:last');
$('<select id="prependSelect2"><option>Test</option></select>').prependTo('form:last');
t( "Prepend Select", "#prependSelect1, #prependSelect2", ["prependSelect1", "prependSelect2"] );
});
test("before(String|Element|Array&lt;Element&gt;|jQuery)", function() {
expect(4);
var expected = 'This is a normal link: bugaYahoo';
$('#yahoo').before('<b>buga</b>');
ok( expected == $('#en').text(), 'Insert String before' );
reset();
expected = "This is a normal link: Try them out:Yahoo";
$('#yahoo').before(document.getElementById('first'));
ok( expected == $('#en').text(), "Insert element before" );
reset();
expected = "This is a normal link: Try them out:diveintomarkYahoo";
$('#yahoo').before([document.getElementById('first'), document.getElementById('mark')]);
ok( expected == $('#en').text(), "Insert array of elements before" );
reset();
expected = "This is a normal link: Try them out:diveintomarkYahoo";
$('#yahoo').before($("#first, #mark"));
ok( expected == $('#en').text(), "Insert jQuery before" );
});
test("insertBefore(String|Element|Array&lt;Element&gt;|jQuery)", function() {
expect(4);
var expected = 'This is a normal link: bugaYahoo';
$('<b>buga</b>').insertBefore('#yahoo');
ok( expected == $('#en').text(), 'Insert String before' );
reset();
expected = "This is a normal link: Try them out:Yahoo";
$(document.getElementById('first')).insertBefore('#yahoo');
ok( expected == $('#en').text(), "Insert element before" );
reset();
expected = "This is a normal link: Try them out:diveintomarkYahoo";
$([document.getElementById('first'), document.getElementById('mark')]).insertBefore('#yahoo');
ok( expected == $('#en').text(), "Insert array of elements before" );
reset();
expected = "This is a normal link: Try them out:diveintomarkYahoo";
$("#first, #mark").insertBefore('#yahoo');
ok( expected == $('#en').text(), "Insert jQuery before" );
});
test("after(String|Element|Array&lt;Element&gt;|jQuery)", function() {
expect(4);
var expected = 'This is a normal link: Yahoobuga';
$('#yahoo').after('<b>buga</b>');
ok( expected == $('#en').text(), 'Insert String after' );
reset();
expected = "This is a normal link: YahooTry them out:";
$('#yahoo').after(document.getElementById('first'));
ok( expected == $('#en').text(), "Insert element after" );
reset();
expected = "This is a normal link: YahooTry them out:diveintomark";
$('#yahoo').after([document.getElementById('first'), document.getElementById('mark')]);
ok( expected == $('#en').text(), "Insert array of elements after" );
reset();
expected = "This is a normal link: YahooTry them out:diveintomark";
$('#yahoo').after($("#first, #mark"));
ok( expected == $('#en').text(), "Insert jQuery after" );
});
test("insertAfter(String|Element|Array&lt;Element&gt;|jQuery)", function() {
expect(4);
var expected = 'This is a normal link: Yahoobuga';
$('<b>buga</b>').insertAfter('#yahoo');
ok( expected == $('#en').text(), 'Insert String after' );
reset();
expected = "This is a normal link: YahooTry them out:";
$(document.getElementById('first')).insertAfter('#yahoo');
ok( expected == $('#en').text(), "Insert element after" );
reset();
expected = "This is a normal link: YahooTry them out:diveintomark";
$([document.getElementById('mark'), document.getElementById('first')]).insertAfter('#yahoo');
ok( expected == $('#en').text(), "Insert array of elements after" );
reset();
expected = "This is a normal link: YahooTry them out:diveintomark";
$("#mark, #first").insertAfter('#yahoo');
ok( expected == $('#en').text(), "Insert jQuery after" );
});
test("end()", function() {
expect(3);
ok( 'Yahoo' == $('#yahoo').parent().end().text(), 'Check for end' );
ok( $('#yahoo').end(), 'Check for end with nothing to end' );
var x = $('#yahoo');
x.parent();
ok( 'Yahoo' == $('#yahoo').text(), 'Check for non-destructive behaviour' );
});
test("find(String)", function() {
expect(1);
ok( 'Yahoo' == $('#foo').find('.blogTest').text(), 'Check for find' );
});
test("clone()", function() {
expect(3);
ok( 'This is a normal link: Yahoo' == $('#en').text(), 'Assert text for #en' );
var clone = $('#yahoo').clone();
ok( 'Try them out:Yahoo' == $('#first').append(clone).text(), 'Check for clone' );
ok( 'This is a normal link: Yahoo' == $('#en').text(), 'Reassert text for #en' );
});
test("is(String)", function() {
expect(26);
ok( $('#form').is('form'), 'Check for element: A form must be a form' );
ok( !$('#form').is('div'), 'Check for element: A form is not a div' );
ok( $('#mark').is('.blog'), 'Check for class: Expected class "blog"' );
ok( !$('#mark').is('.link'), 'Check for class: Did not expect class "link"' );
ok( $('#simon').is('.blog.link'), 'Check for multiple classes: Expected classes "blog" and "link"' );
ok( !$('#simon').is('.blogTest'), 'Check for multiple classes: Expected classes "blog" and "link", but not "blogTest"' );
ok( $('#en').is('[@lang="en"]'), 'Check for attribute: Expected attribute lang to be "en"' );
ok( !$('#en').is('[@lang="de"]'), 'Check for attribute: Expected attribute lang to be "en", not "de"' );
ok( $('#text1').is('[@type="text"]'), 'Check for attribute: Expected attribute type to be "text"' );
ok( !$('#text1').is('[@type="radio"]'), 'Check for attribute: Expected attribute type to be "text", not "radio"' );
ok( $('#text2').is(':disabled'), 'Check for pseudoclass: Expected to be disabled' );
ok( !$('#text1').is(':disabled'), 'Check for pseudoclass: Expected not disabled' );
ok( $('#radio2').is(':checked'), 'Check for pseudoclass: Expected to be checked' );
ok( !$('#radio1').is(':checked'), 'Check for pseudoclass: Expected not checked' );
ok( $('#foo').is('[p]'), 'Check for child: Expected a child "p" element' );
ok( !$('#foo').is('[ul]'), 'Check for child: Did not expect "ul" element' );
ok( $('#foo').is('[p][a][code]'), 'Check for childs: Expected "p", "a" and "code" child elements' );
ok( !$('#foo').is('[p][a][code][ol]'), 'Check for childs: Expected "p", "a" and "code" child elements, but no "ol"' );
ok( !$('#foo').is(0), 'Expected false for an invalid expression - 0' );
ok( !$('#foo').is(null), 'Expected false for an invalid expression - null' );
ok( !$('#foo').is(''), 'Expected false for an invalid expression - ""' );
ok( !$('#foo').is(undefined), 'Expected false for an invalid expression - undefined' );
// test is() with comma-seperated expressions
ok( $('#en').is('[@lang="en"],[@lang="de"]'), 'Comma-seperated; Check for lang attribute: Expect en or de' );
ok( $('#en').is('[@lang="de"],[@lang="en"]'), 'Comma-seperated; Check for lang attribute: Expect en or de' );
ok( $('#en').is('[@lang="en"] , [@lang="de"]'), 'Comma-seperated; Check for lang attribute: Expect en or de' );
ok( $('#en').is('[@lang="de"] , [@lang="en"]'), 'Comma-seperated; Check for lang attribute: Expect en or de' );
});
test("$.extend(Object, Object)", function() {
expect(2);
var settings = { xnumber1: 5, xnumber2: 7, xstring1: "peter", xstring2: "pan" },
options = { xnumber2: 1, xstring2: "x", xxx: "newstring" },
optionsCopy = { xnumber2: 1, xstring2: "x", xxx: "newstring" },
merged = { xnumber1: 5, xnumber2: 1, xstring1: "peter", xstring2: "x", xxx: "newstring" };
jQuery.extend(settings, options);
isObj( settings, merged, "Check if extended: settings must be extended" );
isObj( options, optionsCopy, "Check if not modified: options must not be modified" );
});
test("$.extend(Object, Object, Object, Object)", function() {
expect(4);
var defaults = { xnumber1: 5, xnumber2: 7, xstring1: "peter", xstring2: "pan" },
defaultsCopy = { xnumber1: 5, xnumber2: 7, xstring1: "peter", xstring2: "pan" },
options1 = { xnumber2: 1, xstring2: "x" },
options1Copy = { xnumber2: 1, xstring2: "x" },
options2 = { xstring2: "xx", xxx: "newstringx" },
options2Copy = { xstring2: "xx", xxx: "newstringx" },
merged = { xnumber1: 5, xnumber2: 1, xstring1: "peter", xstring2: "xx", xxx: "newstringx" };
var settings = jQuery.extend({}, defaults, options1, options2);
isObj( settings, merged, "Check if extended: settings must be extended" );
isObj( defaults, defaultsCopy, "Check if not modified: options1 must not be modified" );
isObj( options1, options1Copy, "Check if not modified: options1 must not be modified" );
isObj( options2, options2Copy, "Check if not modified: options2 must not be modified" );
});
test("val()", function() {
expect(2);
ok( $("#text1").val() == "Test", "Check for value of input element" );
ok( !$("#text1").val() == "", "Check for value of input element" );
});
test("val(String)", function() {
expect(2);
document.getElementById('text1').value = "bla";
ok( $("#text1").val() == "bla", "Check for modified value of input element" );
$("#text1").val('test');
ok ( document.getElementById('text1').value == "test", "Check for modified (via val(String)) value of input element" );
});
test("html(String)", function() {
expect(1);
var div = $("div");
div.html("<b>test</b>");
var pass = true;
for ( var i = 0; i < div.size(); i++ ) {
if ( div.get(i).childNodes.length == 0 ) pass = false;
}
ok( pass, "Set HTML" );
// Ccommented out until we can resolve it
// $("#main").html('<script type="text/javascript">ok( true, "$().html().evalScripts() Evals Scripts Twice in Firefox, see #975" );</script>').evalScripts();
});
test("filter()", function() {
expect(4);
isSet( $("input").filter(":checked").get(), q("radio2", "check1"), "filter(String)" );
isSet( $("p").filter("#ap, #sndp").get(), q("ap", "sndp"), "filter('String, String')" );
isSet( $("p").filter("#ap,#sndp").get(), q("ap", "sndp"), "filter('String,String')" );
isSet( $("p").filter(function() { return !$("a", this).length }).get(), q("sndp", "first"), "filter(Function)" );
});
test("not()", function() {
expect(3);
ok( $("#main > p#ap > a").not("#google").length == 2, "not('selector')" );
isSet( $("p").not("#ap, #sndp, .result").get(), q("firstp", "en", "sap", "first"), "not('selector, selector')" );
isSet( $("p").not($("#ap, #sndp, .result")).get(), q("firstp", "en", "sap", "first"), "not(jQuery)" );
});
test("siblings([String])", function() {
expect(4);
isSet( $("#en").siblings().get(), q("sndp", "sap"), "Check for siblings" );
isSet( $("#sndp").siblings("[code]").get(), q("sap"), "Check for filtered siblings (has code child element)" );
isSet( $("#sndp").siblings("[a]").get(), q("en", "sap"), "Check for filtered siblings (has anchor child element)" );
isSet( $("#foo").siblings("form, b").get(), q("form", "lengthtest", "floatTest"), "Check for multiple filters" );
});
test("children([String])", function() {
expect(3);
isSet( $("#foo").children().get(), q("sndp", "en", "sap"), "Check for children" );
isSet( $("#foo").children("[code]").get(), q("sndp", "sap"), "Check for filtered children" );
isSet( $("#foo").children("#en, #sap").get(), q("en", "sap"), "Check for multiple filters" );
});
test("parent[s]([String])", function() {
expect(8);
ok( $("#groups").parent()[0].id == "ap", "Simple parent check" );
ok( $("#groups").parent("p")[0].id == "ap", "Filtered parent check" );
ok( $("#groups").parent("div").length == 0, "Filtered parent check, no match" );
ok( $("#groups").parent("div, p")[0].id == "ap", "Check for multiple filters" );
ok( $("#groups").parents()[0].id == "ap", "Simple parents check" );
ok( $("#groups").parents("p")[0].id == "ap", "Filtered parents check" );
ok( $("#groups").parents("div")[0].id == "main", "Filtered parents check2" );
isSet( $("#groups").parents("p, div").get(), q("ap", "main"), "Check for multiple filters" );
});
test("next/prev([String])", function() {
expect(8);
ok( $("#ap").next()[0].id == "foo", "Simple next check" );
ok( $("#ap").next("div")[0].id == "foo", "Filtered next check" );
ok( $("#ap").next("p").length == 0, "Filtered next check, no match" );
ok( $("#ap").next("div, p")[0].id == "foo", "Multiple filters" );
ok( $("#foo").prev()[0].id == "ap", "Simple prev check" );
ok( $("#foo").prev("p")[0].id == "ap", "Filtered prev check" );
ok( $("#foo").prev("div").length == 0, "Filtered prev check, no match" );
ok( $("#foo").prev("p, div")[0].id == "ap", "Multiple filters" );
});
test("show()", function() {
expect(1);
var pass = true, div = $("div");
div.show().each(function(){
if ( this.style.display == "none" ) pass = false;
});
ok( pass, "Show" );
});
test("addClass(String)", function() {
expect(1);
var div = $("div");
div.addClass("test");
var pass = true;
for ( var i = 0; i < div.size(); i++ ) {
if ( div.get(i).className.indexOf("test") == -1 ) pass = false;
}
ok( pass, "Add Class" );
});
test("removeClass(String) - simple", function() {
expect(3);
var div = $("div").addClass("test").removeClass("test"),
pass = true;
for ( var i = 0; i < div.size(); i++ ) {
if ( div.get(i).className.indexOf("test") != -1 ) pass = false;
}
ok( pass, "Remove Class" );
reset();
var div = $("div").addClass("test").addClass("foo").addClass("bar");
div.removeClass("test").removeClass("bar").removeClass("foo");
var pass = true;
for ( var i = 0; i < div.size(); i++ ) {
if ( div.get(i).className.match(/test|bar|foo/) ) pass = false;
}
ok( pass, "Remove multiple classes" );
reset();
var div = $("div:eq(0)").addClass("test").removeClass("");
ok( div.is('.test'), "Empty string passed to removeClass" );
});
test("toggleClass(String)", function() {
expect(3);
var e = $("#firstp");
ok( !e.is(".test"), "Assert class not present" );
e.toggleClass("test");
ok( e.is(".test"), "Assert class present" );
e.toggleClass("test");
ok( !e.is(".test"), "Assert class not present" );
});
test("removeAttr(String", function() {
expect(1);
ok( $('#mark').removeAttr("class")[0].className == "", "remove class" );
});
test("text(String)", function() {
expect(1);
ok( $("#foo").text("<div><b>Hello</b> cruel world!</div>")[0].innerHTML == "&lt;div&gt;&lt;b&gt;Hello&lt;/b&gt; cruel world!&lt;/div&gt;", "Check escaped text" );
});
test("$.each(Object,Function)", function() {
expect(8);
$.each( [0,1,2], function(i, n){
ok( i == n, "Check array iteration" );
});
$.each( [5,6,7], function(i, n){
ok( i == n - 5, "Check array iteration" );
});
$.each( { name: "name", lang: "lang" }, function(i, n){
ok( i == n, "Check object iteration" );
});
});
test("$.prop", function() {
expect(2);
var handle = function() { return this.id };
ok( $.prop($("#ap")[0], handle) == "ap", "Check with Function argument" );
ok( $.prop($("#ap")[0], "value") == "value", "Check with value argument" );
});
test("$.className", function() {
expect(6);
var x = $("<p>Hi</p>")[0];
var c = $.className;
c.add(x, "hi");
ok( x.className == "hi", "Check single added class" );
c.add(x, "foo bar");
ok( x.className == "hi foo bar", "Check more added classes" );
c.remove(x);
ok( x.className == "", "Remove all classes" );
c.add(x, "hi foo bar");
c.remove(x, "foo");
ok( x.className == "hi bar", "Check removal of one class" );
ok( c.has(x, "hi"), "Check has1" );
ok( c.has(x, "bar"), "Check has2" );
});
test("remove()", function() {
expect(4);
$("#ap").children().remove();
ok( $("#ap").text().length > 10, "Check text is not removed" );
ok( $("#ap").children().length == 0, "Check remove" );
reset();
$("#ap").children().remove("a");
ok( $("#ap").text().length > 10, "Check text is not removed" );
ok( $("#ap").children().length == 1, "Check filtered remove" );
});
test("empty()", function() {
expect(2);
ok( $("#ap").children().empty().text().length == 0, "Check text is removed" );
ok( $("#ap").children().length == 4, "Check elements are not removed" );
});
test("eq(), gt(), lt(), contains()", function() {
expect(4);
ok( $("#ap a").eq(1)[0].id == "groups", "eq()" );
isSet( $("#ap a").gt(0).get(), q("groups", "anchor1", "mark"), "gt()" );
isSet( $("#ap a").lt(3).get(), q("google", "groups", "anchor1"), "lt()" );
isSet( $("#foo a").contains("log").get(), q("anchor2", "simon"), "contains()" );
});

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -1 +0,0 @@
}

Просмотреть файл

@ -1,433 +0,0 @@
jQuery.extend({
expr: {
"": "m[2]=='*'||jQuery.nodeName(a,m[2])",
"#": "a.getAttribute('id')==m[2]",
":": {
// Position Checks
lt: "i<m[3]-0",
gt: "i>m[3]-0",
nth: "m[3]-0==i",
eq: "m[3]-0==i",
first: "i==0",
last: "i==r.length-1",
even: "i%2==0",
odd: "i%2",
// Child Checks
"nth-child": "jQuery.nth(a.parentNode.firstChild,m[3],'nextSibling',a)==a",
"first-child": "jQuery.nth(a.parentNode.firstChild,1,'nextSibling')==a",
"last-child": "jQuery.nth(a.parentNode.lastChild,1,'previousSibling')==a",
"only-child": "jQuery.sibling(a.parentNode.firstChild).length==1",
// Parent Checks
parent: "a.firstChild",
empty: "!a.firstChild",
// Text Check
contains: "jQuery.fn.text.apply([a]).indexOf(m[3])>=0",
// Visibility
visible: '"hidden"!=a.type&&jQuery.css(a,"display")!="none"&&jQuery.css(a,"visibility")!="hidden"',
hidden: '"hidden"==a.type||jQuery.css(a,"display")=="none"||jQuery.css(a,"visibility")=="hidden"',
// Form attributes
enabled: "!a.disabled",
disabled: "a.disabled",
checked: "a.checked",
selected: "a.selected||jQuery.attr(a,'selected')",
// Form elements
text: "'text'==a.type",
radio: "'radio'==a.type",
checkbox: "'checkbox'==a.type",
file: "'file'==a.type",
password: "'password'==a.type",
submit: "'submit'==a.type",
image: "'image'==a.type",
reset: "'reset'==a.type",
button: '"button"==a.type||jQuery.nodeName(a,"button")',
input: "/input|select|textarea|button/i.test(a.nodeName)"
},
".": "jQuery.className.has(a,m[2])",
"@": {
"=": "z==m[4]",
"!=": "z!=m[4]",
"^=": "z&&!z.indexOf(m[4])",
"$=": "z&&z.substr(z.length - m[4].length,m[4].length)==m[4]",
"*=": "z&&z.indexOf(m[4])>=0",
"": "z",
_resort: function(m){
return ["", m[1], m[3], m[2], m[5]];
},
_prefix: "var z=a[m[3]];if(!z||/href|src/.test(m[3]))z=jQuery.attr(a,m[3]);"
},
"[": "jQuery.find(m[2],a).length"
},
// The regular expressions that power the parsing engine
parse: [
// Match: [@value='test'], [@foo]
/^\[ *(@)([\w-]+) *([!*$^=]*) *('?"?)(.*?)\4 *\]/,
// Match: [div], [div p]
/^(\[)\s*(.*?(\[.*?\])?[^[]*?)\s*\]/,
// Match: :contains('foo')
/^(:)([\w-]+)\("?'?(.*?(\(.*?\))?[^(]*?)"?'?\)/,
// Match: :even, :last-chlid, #id, .class
new RegExp("^([:.#]*)(" +
( jQuery.chars = "(?:[\\w\u0128-\uFFFF*_-]|\\\\.)" ) + "+)")
],
token: [
/^(\/?\.\.)/, "a.parentNode",
/^(>|\/)/, "jQuery.sibling(a.firstChild)",
/^(\+)/, "jQuery.nth(a,2,'nextSibling')",
/^(~)/, function(a){
var s = jQuery.sibling(a.parentNode.firstChild);
return s.slice(jQuery.inArray(a,s) + 1);
}
],
multiFilter: function( expr, elems, not ) {
var old, cur = [];
while ( expr && expr != old ) {
old = expr;
var f = jQuery.filter( expr, elems, not );
expr = f.t.replace(/^\s*,\s*/, "" );
cur = not ? elems = f.r : jQuery.merge( cur, f.r );
}
return cur;
},
/**
* @name $.find
* @type Array<Element>
* @private
* @cat Core
*/
find: function( t, context ) {
// Quickly handle non-string expressions
if ( typeof t != "string" )
return [ t ];
// Make sure that the context is a DOM Element
if ( context && !context.nodeType )
context = null;
// Set the correct context (if none is provided)
context = context || document;
// Handle the common XPath // expression
if ( !t.indexOf("//") ) {
context = context.documentElement;
t = t.substr(2,t.length);
// And the / root expression
} else if ( !t.indexOf("/") && !context.ownerDocument ) {
context = context.documentElement;
t = t.substr(1,t.length);
if ( t.indexOf("/") >= 1 )
t = t.substr(t.indexOf("/"),t.length);
}
// Initialize the search
var ret = [context], done = [], last;
// Continue while a selector expression exists, and while
// we're no longer looping upon ourselves
while ( t && last != t ) {
var r = [];
last = t;
t = jQuery.trim(t).replace( /^\/\//, "" );
var foundToken = false;
// An attempt at speeding up child selectors that
// point to a specific element tag
var re = new RegExp("^[/>]\\s*(" + jQuery.chars + "+)");
var m = re.exec(t);
if ( m ) {
// Perform our own iteration and filter
for ( var i = 0; ret[i]; i++ )
for ( var c = ret[i].firstChild; c; c = c.nextSibling )
if ( c.nodeType == 1 && ( m[1] == "*" || jQuery.nodeName(c, m[1]) ) )
r.push( c );
ret = r;
t = t.replace( re, "" );
if ( t.indexOf(" ") == 0 ) continue;
foundToken = true;
} else {
// Look for pre-defined expression tokens
for ( var i = 0, tl = jQuery.token.length; i < tl; i += 2 ) {
// Attempt to match each, individual, token in
// the specified order
var re = jQuery.token[i], fn = jQuery.token[i+1];
var m = re.exec(t);
// If the token match was found
if ( m ) {
// Map it against the token's handler
r = ret = jQuery.map( ret, jQuery.isFunction( fn ) ?
fn : new Function( "a", "return " + fn ) );
// And remove the token
t = jQuery.trim( t.replace( re, "" ) );
foundToken = true;
break;
}
}
}
// See if there's still an expression, and that we haven't already
// matched a token
if ( t && !foundToken ) {
// Handle multiple expressions
if ( !t.indexOf(",") ) {
// Clean the result set
if ( context == ret[0] ) ret.shift();
// Merge the result sets
done = jQuery.merge( done, ret );
// Reset the context
r = ret = [context];
// Touch up the selector string
t = " " + t.substr(1,t.length);
} else {
// Optomize for the case nodeName#idName
var re2 = new RegExp("^(" + jQuery.chars + "+)(#)(" + jQuery.chars + "+)");
var m = re2.exec(t);
// Re-organize the results, so that they're consistent
if ( m ) {
m = [ 0, m[2], m[3], m[1] ];
} else {
// Otherwise, do a traditional filter check for
// ID, class, and element selectors
re2 = new RegExp("^([#.]?)(" + jQuery.chars + "*)");
m = re2.exec(t);
}
m[2] = m[2].replace(/\\/g, "");
var elem = ret[ret.length-1];
// Try to do a global search by ID, where we can
if ( m[1] == "#" && elem && elem.getElementById ) {
// Optimization for HTML document case
var oid = elem.getElementById(m[2]);
// Do a quick check for the existence of the actual ID attribute
// to avoid selecting by the name attribute in IE
// also check to insure id is a string to avoid selecting an element with the name of 'id' inside a form
if ( (jQuery.browser.msie||jQuery.browser.opera) && oid && typeof oid.id == "string" && oid.id != m[2] )
oid = jQuery('[@id="'+m[2]+'"]', elem)[0];
// Do a quick check for node name (where applicable) so
// that div#foo searches will be really fast
ret = r = oid && (!m[3] || jQuery.nodeName(oid, m[3])) ? [oid] : [];
} else {
// We need to find all descendant elements
for ( var i = 0; ret[i]; i++ ) {
// Grab the tag name being searched for
var tag = m[1] != "" || m[0] == "" ? "*" : m[2];
// Handle IE7 being really dumb about <object>s
if ( tag == "*" && ret[i].nodeName.toLowerCase() == "object" )
tag = "param";
r = jQuery.merge( r, ret[i].getElementsByTagName( tag ));
}
// It's faster to filter by class and be done with it
if ( m[1] == "." )
r = jQuery.classFilter( r, m[2] );
// Same with ID filtering
if ( m[1] == "#" ) {
var tmp = [];
// Try to find the element with the ID
for ( var i = 0; r[i]; i++ )
if ( r[i].getAttribute("id") == m[2] ) {
tmp = [ r[i] ];
break;
}
r = tmp;
}
ret = r;
}
t = t.replace( re2, "" );
}
}
// If a selector string still exists
if ( t ) {
// Attempt to filter it
var val = jQuery.filter(t,r);
ret = r = val.r;
t = jQuery.trim(val.t);
}
}
// An error occurred with the selector;
// just return an empty set instead
if ( t )
ret = [];
// Remove the root context
if ( ret && context == ret[0] )
ret.shift();
// And combine the results
done = jQuery.merge( done, ret );
return done;
},
classFilter: function(r,m,not){
m = " " + m + " ";
var tmp = [];
for ( var i = 0; r[i]; i++ ) {
var pass = (" " + r[i].className + " ").indexOf( m ) >= 0;
if ( !not && pass || not && !pass )
tmp.push( r[i] );
}
return tmp;
},
filter: function(t,r,not) {
var last;
// Look for common filter expressions
while ( t && t != last ) {
last = t;
var p = jQuery.parse, m;
for ( var i = 0; p[i]; i++ ) {
m = p[i].exec( t );
if ( m ) {
// Remove what we just matched
t = t.substring( m[0].length );
// Re-organize the first match
if ( jQuery.expr[ m[1] ]._resort )
m = jQuery.expr[ m[1] ]._resort( m );
m[2] = m[2].replace(/\\/g, "");
break;
}
}
if ( !m )
break;
// :not() is a special case that can be optimized by
// keeping it out of the expression list
if ( m[1] == ":" && m[2] == "not" )
r = jQuery.filter(m[3], r, true).r;
// We can get a big speed boost by filtering by class here
else if ( m[1] == "." )
r = jQuery.classFilter(r, m[2], not);
// Otherwise, find the expression to execute
else {
var f = jQuery.expr[m[1]];
if ( typeof f != "string" )
f = jQuery.expr[m[1]][m[2]];
// Build a custom macro to enclose it
eval("f = function(a,i){" +
( jQuery.expr[ m[1] ]._prefix || "" ) +
"return " + f + "}");
// Execute it against the current filter
r = jQuery.grep( r, f, not );
}
}
// Return an array of filtered elements (r)
// and the modified expression string (t)
return { r: r, t: t };
},
/**
* All ancestors of a given element.
*
* @private
* @name $.parents
* @type Array<Element>
* @param Element elem The element to find the ancestors of.
* @cat DOM/Traversing
*/
parents: function( elem ){
var matched = [];
var cur = elem.parentNode;
while ( cur && cur != document ) {
matched.push( cur );
cur = cur.parentNode;
}
return matched;
},
/**
* A handy, and fast, way to traverse in a particular direction and find
* a specific element.
*
* @private
* @name $.nth
* @type DOMElement
* @param DOMElement cur The element to search from.
* @param String|Number num The Nth result to match. Can be a number or a string (like 'even' or 'odd').
* @param String dir The direction to move in (pass in something like 'previousSibling' or 'nextSibling').
* @cat DOM/Traversing
*/
nth: function(cur,result,dir,elem){
result = result || 1;
var num = 0;
for ( ; cur; cur = cur[dir] ) {
if ( cur.nodeType == 1 ) num++;
if ( num == result || result == "even" && num % 2 == 0 && num > 1 && cur == elem ||
result == "odd" && num % 2 == 1 && cur == elem ) break;
}
return cur;
},
/**
* All elements on a specified axis.
*
* @private
* @name $.sibling
* @type Array
* @param Element elem The element to find all the siblings of (including itself).
* @cat DOM/Traversing
*/
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType == 1 && (!elem || n != elem) )
r.push( n );
}
return r;
}
});

Просмотреть файл

@ -1,204 +0,0 @@
module("selector");
test("element", function() {
expect(9);
ok( $("*").size() >= 30, "Select all" );
t( "Element Selector", "div", ["main","foo"] );
t( "Element Selector", "body", ["body"] );
t( "Element Selector", "html", ["html"] );
t( "Parent Element", "div div", ["foo"] );
ok( $("param", "#object1").length == 2, "Object/param as context" );
ok( $("#length").length, '&lt;input name="length"&gt; cannot be found under IE, see #945' );
ok( $("#lengthtest input").length, '&lt;input name="length"&gt; cannot be found under IE, see #945' );
t( "Element Selector with underscore", "foo_bar", ["foobar"] );
});
test("broken", function() {
expect(7);
t( "Broken Selector", "[", [] );
t( "Broken Selector", "(", [] );
t( "Broken Selector", "{", [] );
t( "Broken Selector", "<", [] );
t( "Broken Selector", "()", [] );
t( "Broken Selector", "<>", [] );
t( "Broken Selector", "{}", [] );
});
test("id", function() {
expect(24);
t( "ID Selector", "#body", ["body"] );
t( "ID Selector w/ Element", "body#body", ["body"] );
t( "ID Selector w/ Element", "ul#first", [] );
t( "ID selector with existing ID descendant", "#firstp #simon1", ["simon1"] );
t( "ID selector with non-existant descendant", "#firstp #foobar", [] );
t( "ID selector using UTF8", "#台北Táiběi", ["台北Táiběi"] );
t( "Multiple ID selectors using UTF8", "#台北Táiběi, #台北", ["台北Táiběi","台北"] );
t( "Descendant ID selector using UTF8", "div #台北", ["台北"] );
t( "Child ID selector using UTF8", "form > #台北", ["台北"] );
t( "Escaped ID", "#foo\\:bar", ["foo:bar"] );
t( "Escaped ID", "#test\\.foo\\[5\\]bar", ["test.foo[5]bar"] );
t( "Descendant escaped ID", "div #foo\\:bar", ["foo:bar"] );
t( "Descendant escaped ID", "div #test\\.foo\\[5\\]bar", ["test.foo[5]bar"] );
t( "Child escaped ID", "form > #foo\\:bar", ["foo:bar"] );
t( "Child escaped ID", "form > #test\\.foo\\[5\\]bar", ["test.foo[5]bar"] );
t( "ID Selector, child ID present", "#form > #radio1", ["radio1"] ); // bug #267
t( "ID Selector, not an ancestor ID", "#form #first", [] );
t( "ID Selector, not a child ID", "#form > #option1a", [] );
t( "All Children of ID", "#foo/*", ["sndp", "en", "sap"] );
t( "All Children of ID with no children", "#firstUL/*", [] );
$('<a name="tName1">tName1 A</a><a name="tName2">tName2 A</a><div id="tName1">tName1 Div</div>').appendTo('#main');
ok( $("#tName1")[0].id == 'tName1', "ID selector with same value for a name attribute" );
ok( $("#tName2").length == 0, "ID selector non-existing but name attribute on an A tag" );
t( "ID Selector on Form with an input that has a name of 'id'", "#lengthtest", ["lengthtest"] );
t( "ID selector with non-existant ancestor", "#asdfasdf #foobar", [] ); // bug #986
});
test("class", function() {
expect(16);
t( "Class Selector", ".blog", ["mark","simon"] );
t( "Class Selector", ".blog.link", ["simon"] );
t( "Class Selector w/ Element", "a.blog", ["mark","simon"] );
t( "Parent Class Selector", "p .blog", ["mark","simon"] );
t( "Class selector using UTF8", ".台北Táiběi", ["utf8class1"] );
t( "Class selector using UTF8", ".台北", ["utf8class1","utf8class2"] );
t( "Class selector using UTF8", ".台北Táiběi.台北", ["utf8class1"] );
t( "Class selector using UTF8", ".台北Táiběi, .台北", ["utf8class1","utf8class2"] );
t( "Descendant class selector using UTF8", "div .台北Táiběi", ["utf8class1"] );
t( "Child class selector using UTF8", "form > .台北Táiběi", ["utf8class1"] );
t( "Escaped Class", ".foo\\:bar", ["foo:bar"] );
t( "Escaped Class", ".test\\.foo\\[5\\]bar", ["test.foo[5]bar"] );
t( "Descendant scaped Class", "div .foo\\:bar", ["foo:bar"] );
t( "Descendant scaped Class", "div .test\\.foo\\[5\\]bar", ["test.foo[5]bar"] );
t( "Child escaped Class", "form > .foo\\:bar", ["foo:bar"] );
t( "Child escaped Class", "form > .test\\.foo\\[5\\]bar", ["test.foo[5]bar"] );
});
test("multiple", function() {
expect(4);
t( "Comma Support", "a.blog, div", ["mark","simon","main","foo"] );
t( "Comma Support", "a.blog , div", ["mark","simon","main","foo"] );
t( "Comma Support", "a.blog ,div", ["mark","simon","main","foo"] );
t( "Comma Support", "a.blog,div", ["mark","simon","main","foo"] );
});
test("child and adjacent", function() {
expect(18);
t( "Child", "p > a", ["simon1","google","groups","mark","yahoo","simon"] );
t( "Child", "p> a", ["simon1","google","groups","mark","yahoo","simon"] );
t( "Child", "p >a", ["simon1","google","groups","mark","yahoo","simon"] );
t( "Child", "p>a", ["simon1","google","groups","mark","yahoo","simon"] );
t( "Child w/ Class", "p > a.blog", ["mark","simon"] );
t( "All Children", "code > *", ["anchor1","anchor2"] );
t( "All Grandchildren", "p > * > *", ["anchor1","anchor2"] );
t( "Adjacent", "a + a", ["groups"] );
t( "Adjacent", "a +a", ["groups"] );
t( "Adjacent", "a+ a", ["groups"] );
t( "Adjacent", "a+a", ["groups"] );
t( "Adjacent", "p + p", ["ap","en","sap"] );
t( "Comma, Child, and Adjacent", "a + a, code > a", ["groups","anchor1","anchor2"] );
t( "First Child", "p:first-child", ["firstp","sndp"] );
t( "Nth Child", "p:nth-child(1)", ["firstp","sndp"] );
t( "Last Child", "p:last-child", ["sap"] );
t( "Nth-child", "#main form > *:nth-child(2)", ["text2","idTest"] );
t( "Nth-child", "#main form > :nth-child(2)", ["text2","idTest"] );
});
test("attributes", function() {
expect(20);
t( "Attribute Exists", "a[@title]", ["google"] );
t( "Attribute Exists", "*[@title]", ["google"] );
t( "Attribute Exists", "[@title]", ["google"] );
t( "Attribute Equals", "a[@rel='bookmark']", ["simon1"] );
t( "Attribute Equals", 'a[@rel="bookmark"]', ["simon1"] );
t( "Attribute Equals", "a[@rel=bookmark]", ["simon1"] );
t( "Multiple Attribute Equals", "input[@type='hidden'],input[@type='radio']", ["hidden1","radio1","radio2"] );
t( "Multiple Attribute Equals", "input[@type=\"hidden\"],input[@type='radio']", ["hidden1","radio1","radio2"] );
t( "Multiple Attribute Equals", "input[@type=hidden],input[@type=radio]", ["hidden1","radio1","radio2"] );
t( "Attribute selector using UTF8", "span[@lang=中文]", ["台北"] );
t( "Attribute Begins With", "a[@href ^= 'http://www']", ["google","yahoo"] );
t( "Attribute Ends With", "a[@href $= 'org/']", ["mark"] );
t( "Attribute Contains", "a[@href *= 'google']", ["google","groups"] );
t("Select options via [@selected]", "#select1 option[@selected]", ["option1a"] );
t("Select options via [@selected]", "#select2 option[@selected]", ["option2d"] );
t("Select options via [@selected]", "#select3 option[@selected]", ["option3b", "option3c"] );
t( "Grouped Form Elements", "input[@name='foo[bar]']", ["hidden2"] );
t( ":not() Existing attribute", "select:not([@multiple])", ["select1", "select2"]);
t( ":not() Equals attribute", "select:not([@name=select1])", ["select2", "select3"]);
t( ":not() Equals quoted attribute", "select:not([@name='select1'])", ["select2", "select3"]);
});
test("pseudo (:) selectors", function() {
expect(30);
t( "First Child", "p:first-child", ["firstp","sndp"] );
t( "Last Child", "p:last-child", ["sap"] );
t( "Only Child", "a:only-child", ["simon1","anchor1","yahoo","anchor2"] );
t( "Empty", "ul:empty", ["firstUL"] );
t( "Enabled UI Element", "input:enabled", ["text1","radio1","radio2","check1","check2","hidden1","hidden2","name","length","idTest"] );
t( "Disabled UI Element", "input:disabled", ["text2"] );
t( "Checked UI Element", "input:checked", ["radio2","check1"] );
t( "Selected Option Element", "option:selected", ["option1a","option2d","option3b","option3c"] );
t( "Text Contains", "a:contains('Google')", ["google","groups"] );
t( "Text Contains", "a:contains('Google Groups')", ["groups"] );
t( "Element Preceded By", "p ~ div", ["foo"] );
t( "Not", "a.blog:not(.link)", ["mark"] );
t( "nth Element", "p:nth(1)", ["ap"] );
t( "First Element", "p:first", ["firstp"] );
t( "Last Element", "p:last", ["first"] );
t( "Even Elements", "p:even", ["firstp","sndp","sap"] );
t( "Odd Elements", "p:odd", ["ap","en","first"] );
t( "Position Equals", "p:eq(1)", ["ap"] );
t( "Position Greater Than", "p:gt(0)", ["ap","sndp","en","sap","first"] );
t( "Position Less Than", "p:lt(3)", ["firstp","ap","sndp"] );
t( "Is A Parent", "p:parent", ["firstp","ap","sndp","en","sap","first"] );
t( "Is Visible", "input:visible", ["text1","text2","radio1","radio2","check1","check2","name","length","idTest"] );
t( "Is Hidden", "input:hidden", ["hidden1","hidden2"] );
t( "Form element :input", ":input", ["text1", "text2", "radio1", "radio2", "check1", "check2", "hidden1", "hidden2", "name", "button", "area1", "select1", "select2", "select3", "length", "idTest"] );
t( "Form element :radio", ":radio", ["radio1", "radio2"] );
t( "Form element :checkbox", ":checkbox", ["check1", "check2"] );
t( "Form element :text", ":text", ["text1", "text2", "hidden2", "name", "length", "idTest"] );
t( "Form element :radio:checked", ":radio:checked", ["radio2"] );
t( "Form element :checkbox:checked", ":checkbox:checked", ["check1"] );
t( "Form element :checkbox:checked, :radio:checked", ":checkbox:checked, :radio:checked", ["check1", "radio2"] );
});
test("basic xpath", function() {
expect(15);
ok( jQuery.find("//*").length >= 30, "All Elements (//*)" );
t( "All Div Elements", "//div", ["main","foo"] );
t( "Absolute Path", "/html/body", ["body"] );
t( "Absolute Path w/ *", "/* /body", ["body"] );
t( "Long Absolute Path", "/html/body/dl/div/div/p", ["sndp","en","sap"] );
t( "Absolute and Relative Paths", "/html//div", ["main","foo"] );
t( "All Children, Explicit", "//code/*", ["anchor1","anchor2"] );
t( "All Children, Implicit", "//code/", ["anchor1","anchor2"] );
t( "Attribute Exists", "//a[@title]", ["google"] );
t( "Attribute Equals", "//a[@rel='bookmark']", ["simon1"] );
t( "Parent Axis", "//p/..", ["main","foo"] );
t( "Sibling Axis", "//p/../", ["firstp","ap","foo","first","firstUL","empty","form","floatTest","iframe","lengthtest","table","sndp","en","sap"] );
t( "Sibling Axis", "//p/../*", ["firstp","ap","foo","first","firstUL","empty","form","floatTest","iframe","lengthtest","table","sndp","en","sap"] );
t( "Has Children", "//p[a]", ["firstp","ap","en","sap"] );
$("#foo").each(function() {
isSet( $("/p", this).get(), q("sndp", "en", "sap"), "Check XPath context" );
});
});

Просмотреть файл

@ -45,12 +45,16 @@ include $(DEPTH)/config/autoconf.mk
DIRS = \
data \
unit \
$(NULL)
include $(topsrcdir)/config/rules.mk
_TEST_FILES = \
index.html \
offset.html \
test.js \
fix.html \
$(NULL)
libs:: $(_TEST_FILES)

Просмотреть файл

@ -44,13 +44,25 @@ relativesrcdir = dom/tests/mochitest/ajax/jquery/test/data
include $(DEPTH)/config/autoconf.mk
DIRS = \
offset \
$(NULL)
include $(topsrcdir)/config/rules.mk
_TEST_FILES = \
cow.jpg \
dashboard.xml \
iframe.html \
json_assigned_obj.js \
json_obj.js \
name.html \
test.html \
test.js \
test2.html \
test3.html \
testrunner.js \
testsuite.css \
with_fries.xml \
$(NULL)
libs:: $(_TEST_FILES)

Двоичные данные
dom/tests/mochitest/ajax/jquery/test/data/cow.jpg Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 1.6 KiB

Просмотреть файл

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<dashboard>
<locations class="foo">
<location for="bar">
<infowindowtab>
<tab title="Location"><![CDATA[blabla]]></tab>
<tab title="Users"><![CDATA[blublu]]></tab>
</infowindowtab>
</location>
</locations>
</dashboard>

Просмотреть файл

@ -0,0 +1,8 @@
<html>
<head>
<title>iframe</title>
</head>
<body>
<div><span>span text</span></div>
</body>
</html>

Просмотреть файл

@ -0,0 +1 @@
json_assigned_obj = { "test" : "worked" };

1
dom/tests/mochitest/ajax/jquery/test/data/json_obj.js поставляемый Normal file
Просмотреть файл

@ -0,0 +1 @@
{ "data": {"lang": "en", "length": 25} }

Просмотреть файл

@ -0,0 +1 @@
ERROR <script type="text/javascript">ok( true, "name.html retrieved" );</script>

Просмотреть файл

@ -35,27 +35,26 @@
#
# ***** END LICENSE BLOCK *****
DEPTH = ../../../../../..
DEPTH = ../../../../../../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
relativesrcdir = dom/tests/mochitest/ajax/jquery/src
relativesrcdir = dom/tests/mochitest/ajax/jquery/test/data/offset
include $(DEPTH)/config/autoconf.mk
DIRS = \
ajax \
event \
fx \
jquery \
selector \
$(NULL)
include $(topsrcdir)/config/rules.mk
_TEST_FILES = \
intro.js \
outro.js \
absolute.html \
fixed.html \
relative.html \
scroll.html \
static.html \
table.html \
$(NULL)
libs:: $(_TEST_FILES)

Просмотреть файл

@ -0,0 +1,39 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>absolute</title>
<style type="text/css" media="screen">
body { margin: 1px; padding: 5px; }
div.absolute { position: absolute; margin: 1px; border: 2px solid #000; padding: 5px; width: 100px; height: 100px; background: #fff; }
#absolute-1 { top: 0; left: 0; }
#absolute-1-1 { top: 1px; left: 1px; }
#absolute-1-1-1 { top: 1px; left: 1px; }
#absolute-2 { top: 19px; left: 19px; }
#marker { position: absolute; border: 2px solid #000; width: 50px; height: 50px; background: #ccc; }
p.instructions { position: absolute; bottom: 0; }
</style>
<script type="text/javascript" src="../../../dist/jquery.js"></script>
<script type="text/javascript" charset="utf-8">
$(function() {
$('.absolute').click(function() {
$('#marker').css( $(this).offset() );
var pos = $(this).position();
$(this).css({ top: pos.top, left: pos.left });
return false;
});
});
</script>
</head>
<body>
<div id="absolute-1" class="absolute">absolute-1
<div id="absolute-1-1" class="absolute">absolute-1-1
<div id="absolute-1-1-1" class="absolute">absolute-1-1-1</div>
</div>
</div>
<div id="absolute-2" class="absolute">absolute-2</div>
<div id="marker"></div>
<p class="instructions">Click the white box to move the marker to it. Clicking the box also changes the position to absolute (if not already) and sets the position according to the position method.</p>
</body>
</html>

Просмотреть файл

@ -0,0 +1,33 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>fixed</title>
<style type="text/css" media="screen">
body { margin: 1px; padding: 5px; }
div.fixed { position: fixed; margin: 1px; border: 2px solid #000; padding: 5px; width: 100px; height: 100px; background: #fff; overflow: hidden; }
#fixed-1 { top: 0; left: 0; }
#fixed-2 { top: 20px; left: 20px; }
#forceScroll { width: 5000px; height: 5000px; }
#marker { position: absolute; border: 2px solid #000; width: 50px; height: 50px; background: #ccc; }
</style>
<script type="text/javascript" src="../../../dist/jquery.js"></script>
<script type="text/javascript" charset="utf-8">
$(function() {
window.scrollTo(1000,1000);
$('.fixed').click(function() {
$('#marker').css( $(this).offset() );
return false;
});
});
</script>
</head>
<body>
<div id="fixed-1" class="fixed"></div>
<div id="fixed-2" class="fixed"></div>
<div id="forceScroll"></div>
<div id="marker"></div>
<p class="instructions">Click the white box to move the marker to it.</p>
</body>
</html>

Просмотреть файл

@ -0,0 +1,31 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>relative</title>
<style type="text/css" media="screen">
body { margin: 1px; padding: 5px; }
div.relative { position: relative; margin: 1px; border: 2px solid #000; padding: 5px; width: 100px; height: 100px; background: #fff; overflow: hidden; }
#relative-2 { top: 20px; left: 20px; }
#marker { position: absolute; border: 2px solid #000; width: 50px; height: 50px; background: #ccc; }
</style>
<script type="text/javascript" src="../../../dist/jquery.js"></script>
<script type="text/javascript" charset="utf-8">
$(function() {
$('.relative').click(function() {
$('#marker').css( $(this).offset() );
var pos = $(this).position();
$(this).css({ position: 'absolute', top: pos.top, left: pos.left });
return false;
});
});
</script>
</head>
<body>
<div id="relative-1" class="relative"><div id="relative-1-1" class="relative"><div id="relative-1-1-1" class="relative"></div></div></div>
<div id="relative-2" class="relative"></div>
<div id="marker"></div>
<p class="instructions">Click the white box to move the marker to it. Clicking the box also changes the position to absolute (if not already) and sets the position according to the position method.</p>
</body>
</html>

Просмотреть файл

@ -0,0 +1,39 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>scroll</title>
<style type="text/css" media="screen">
body { margin: 1px; padding: 5px; }
div.scroll { position: relative; margin: 1px; border: 2px solid #000; padding: 5px; width: 100px; height: 100px; background: #fff; overflow: auto; }
#scroll-1 { top: 0; left: 0; }
#scroll-1-1 { top: 1px; left: 1px; }
#scroll-1-1-1 { top: 1px; left: 1px; }
#forceScroll { width: 5000px; height: 5000px; }
#marker { position: absolute; border: 2px solid #000; width: 50px; height: 50px; background: #ccc; }
</style>
<script type="text/javascript" src="../../../dist/jquery.js"></script>
<script type="text/javascript" charset="utf-8">
$(function() {
window.scrollTo(1000,1000);
$('#scroll-1')[0].scrollLeft = 5;
$('#scroll-1')[0].scrollTop = 5;
$('.scroll').click(function() {
$('#marker').css( $(this).offset() );
return false;
});
});
</script>
</head>
<body>
<div id="scroll-1" class="scroll">
<div id="scroll-1-1" class="scroll">
<div id="scroll-1-1-1" class="scroll"></div>
</div>
</div>
<div id="forceScroll"></div>
<div id="marker"></div>
<p class="instructions">Click the white box to move the marker to it.</p>
</body>
</html>

Просмотреть файл

@ -0,0 +1,31 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>static</title>
<style type="text/css" media="screen">
body { margin: 1px; padding: 5px; }
div.static { position: static; margin: 1px; border: 2px solid #000; padding: 5px; width: 100px; height: 100px; background: #fff; overflow: hidden; }
#static-2 { top: 20px; left: 20px; }
#marker { position: absolute; border: 2px solid #000; width: 50px; height: 50px; background: #ccc; }
</style>
<script type="text/javascript" src="../../../dist/jquery.js"></script>
<script type="text/javascript" charset="utf-8">
$(function() {
$('.static').click(function() {
$('#marker').css( $(this).offset() );
var pos = $(this).position();
$(this).css({ position: 'absolute', top: pos.top, left: pos.left });
return false;
});
});
</script>
</head>
<body>
<div id="static-1" class="static"><div id="static-1-1" class="static"><div id="static-1-1-1" class="static"></div></div></div>
<div id="static-2" class="static"></div>
<div id="marker"></div>
<p class="instructions">Click the white box to move the marker to it. Clicking the box also changes the position to absolute (if not already) and sets the position according to the position method.</p>
</body>
</html>

Просмотреть файл

@ -0,0 +1,43 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>table</title>
<style type="text/css" media="screen">
body { margin: 1px; padding: 5px; }
table { border: 2px solid #000; }
th, td { border: 1px solid #000; width: 100px; height: 100px; }
#marker { position: absolute; border: 2px solid #000; width: 50px; height: 50px; background: #ccc; }
</style>
<script type="text/javascript" src="../../../dist/jquery.js"></script>
<script type="text/javascript" charset="utf-8">
$(function() {
$('table, th, td').click(function() {
$('#marker').css( $(this).offset() );
return false;
});
});
</script>
</head>
<body>
<table id="table-1">
<thead>
<tr valign="top">
<th id="th-1">th-1</th>
<th id="th-2">th-2</th>
<th id="th-3">th-3</th>
</tr>
</thead>
<tbody>
<tr valign="top">
<td id="td-1">td-1</td>
<td id="td-2">td-2</td>
<td id="td-3">td-3</td>
</tr>
</tbody>
</table>
<div id="marker"></div>
<p class="instructions">Click the white box to move the marker to it.</p>
</body>
</html>

Просмотреть файл

@ -0,0 +1,7 @@
html text<br/>
<script type="text/javascript">/* <![CDATA[ */
testFoo = "foo"; $('#foo').html('foo');
ok( true, "test.html executed" );
/* ]]> */</script>
<script src="data/test.js"></script>
blabla

3
dom/tests/mochitest/ajax/jquery/test/data/test.js поставляемый Normal file
Просмотреть файл

@ -0,0 +1,3 @@
var foobar = "bar";
$('#ap').html('bar');
ok( true, "test.js executed");

Просмотреть файл

@ -0,0 +1,5 @@
<script type="text/javascript">
var testFoo = "foo";
$('#foo').html('foo');
ok( true, "test2.html executed" );
</script>

Просмотреть файл

@ -0,0 +1,3 @@
<div class="user">This is a user</div>
<div class="user">This is a user</div>
<div class="teacher">This is a teacher</div>

Просмотреть файл

@ -13,6 +13,11 @@ var _config = {
asyncTimeout: 2 // seconds for async timeout
};
_config.filters = location.search.length > 1 && //restrict modules/tests by get parameters
$.map( location.search.slice(1).split('&'), decodeURIComponent );
var isLocal = !!(window.location.protocol == 'file:');
$(function() {
$('#userAgent').html(navigator.userAgent);
runTest();
@ -39,19 +44,44 @@ function stop(allowFailure) {
ok( false, "Test timed out" );
start();
};
_config.timeout = setTimeout(handler, _config.asyncTimeout * 1000);
// Disabled, caused too many random errors
//_config.timeout = setTimeout(handler, _config.asyncTimeout * 1000);
}
function start() {
if(_config.timeout)
clearTimeout(_config.timeout);
_config.blocking = false;
process();
// A slight delay, to avoid any current callbacks
setTimeout(function(){
if(_config.timeout)
clearTimeout(_config.timeout);
_config.blocking = false;
process();
}, 13);
}
function validTest( name ) {
var filters = _config.filters;
if( !filters )
return true;
var i = filters.length,
run = false;
while( i-- ){
var filter = filters[i],
not = filter.charAt(0) == '!';
if( not )
filter = filter.slice(1);
if( name.indexOf(filter) != -1 )
return !not;
if( not )
run = true;
}
return run;
}
function runTest() {
_config.blocking = false;
var time = new Date();
_config.fixture = document.getElementById('main').innerHTML;
_config.ajaxSettings = $.ajaxSettings;
synchronize(function() {
time = new Date() - time;
$("<div>").html(['<p class="result">Tests completed in ',
@ -62,6 +92,7 @@ function runTest() {
$("#banner").addClass(_config.stats.bad ? "fail" : "pass");
if ( parent.runAJAXTest )
parent.runAJAXTest();
});
}
@ -69,8 +100,7 @@ function test(name, callback, nowait) {
if(_config.currentModule)
name = _config.currentModule + " module: " + name;
var filter = location.search.slice(1);
if ( filter && encodeURIComponent(name) != filter )
if ( !validTest(name) )
return;
synchronize(function() {
@ -83,7 +113,7 @@ function test(name, callback, nowait) {
console.error(e);
console.warn(callback.toString());
}
_config.Test.push( [ false, "Died on test #" + (_config.Test.length+1) + ": " + e ] );
_config.Test.push( [ false, "Died on test #" + (_config.Test.length+1) + ": " + e.message ] );
}
});
synchronize(function() {
@ -113,9 +143,9 @@ function test(name, callback, nowait) {
bad++;
_config.stats.bad++;
} else good++;
if ( parent.SimpleTest )
parent.SimpleTest.ok( _config.Test[i][0], name, _config.Test[i][1] );
if ( parent.SimpleTest ){
parent.SimpleTest.ok( _config.Test[i][0], name, _config.Test[i][1] );}
}
var li = document.createElement("li");
@ -160,7 +190,9 @@ function expect(asserts) {
* Resets the test setup. Useful for tests that modify the DOM.
*/
function reset() {
document.getElementById('main').innerHTML = _config.fixture;
$("#main").html( _config.fixture );
$.event.global = {};
$.ajaxSettings = $.extend({}, _config.ajaxSettings);
}
/**
@ -223,7 +255,7 @@ function serialArray( a ) {
r.push( str );
}
return "[ " + r.join(", ") + " ]"
return "[ " + r.join(", ") + " ]";
}
/**
@ -272,11 +304,11 @@ function url(value) {
*
* @example equals( "Expected 2 characters.", v.formatMessage("Expected {0} characters.", 2) );
*
* @param Object expected
* @param Object actual
* @param Object expected
* @param String message (optional)
*/
function equals(expected, actual, message) {
function equals(actual, expected, message) {
var result = expected == actual;
message = message || (result ? "okay" : "failed");
_config.Test.push( [ result, result ? message + ": " + expected : message + " expected: " + expected + " actual: " + actual ] );
@ -299,4 +331,4 @@ function triggerEvent( elem, type, event ) {
} else if ( jQuery.browser.msie ) {
elem.fireEvent("on"+type);
}
}
}

Просмотреть файл

@ -9,4 +9,109 @@ p.result { margin-left: 1em; }
#banner { height: 2em; border-bottom: 1px solid white; }
h2.pass { background-color: green; }
h2.fail { background-color: red; }
h2.fail { background-color: red; }
ol#tests > li > strong { cursor:pointer; }
div#fx-tests h4 {
background: red;
}
div#fx-tests h4.pass {
background: green;
}
div#fx-tests div.box {
background: red url(data/cow.jpg) no-repeat;
overflow: hidden;
border: 2px solid #000;
}
div#fx-tests div.overflow {
overflow: visible;
}
div.inline {
display: inline;
}
div.autoheight {
height: auto;
}
div.autowidth {
width: auto;
}
div.autoopacity {
opacity: auto;
}
div.largewidth {
width: 100px;
}
div.largeheight {
height: 100px;
}
div.largeopacity {
filter: progid:DXImageTransform.Microsoft.Alpha(opacity=100);
}
div.medwidth {
width: 50px;
}
div.medheight {
height: 50px;
}
div.medopacity {
opacity: 0.5;
filter: progid:DXImageTransform.Microsoft.Alpha(opacity=50);
}
div.nowidth {
width: 0px;
}
div.noheight {
height: 0px;
}
div.noopacity {
opacity: 0;
filter: progid:DXImageTransform.Microsoft.Alpha(opacity=0);
}
div.hidden {
display: none;
}
div#fx-tests div.widewidth {
background-repeat: repeat-x;
}
div#fx-tests div.wideheight {
background-repeat: repeat-y;
}
div#fx-tests div.widewidth.wideheight {
background-repeat: repeat;
}
div#fx-tests div.noback {
background-image: none;
}
div.chain, div.chain div { width: 100px; height: 20px; position: relative; float: left; }
div.chain div { position: absolute; top: 0px; left: 0px; }
div.chain.test { background: red; }
div.chain.test div { background: green; }
div.chain.out { background: green; }
div.chain.out div { background: red; display: none; }
div#show-tests * { display: none; }

Просмотреть файл

@ -0,0 +1,25 @@
<?xml version='1.0' encoding='UTF-8'?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soap:Body>
<jsconf xmlns="http://www.example.com/ns1">
<response xmlns:ab="http://www.example.com/ns2">
<meta>
<component id="seite1">
<properties xmlns:cd="http://www.example.com/ns3">
<property name="prop1">
<thing />
<value>1</value>
</property>
<property name="prop2">
<thing att="something" />
</property>
<foo_bar>foo</foo_bar>
</properties>
</component>
</meta>
</response>
</jsconf>
</soap:Body>
</soap:Envelope>

Просмотреть файл

@ -0,0 +1,48 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="generator"
content="HTML Tidy, see www.w3.org" />
<title>Tester</title>
<style type="text/css">
#container { background:yellow; width:400px; height:400px; }
</style>
<script type="text/javascript" src="../dist/jquery.js">
</script>
<script type="text/javascript">
function doIt() {
$("#adiv").text("click!");
$("#adiv").trigger("acustom.atype");
}
function showMouse(e) {
$("#adiv").text("( " + e.pageX + ", " + e.pageY + " )");
}
$(function () {
$("#doit").bind('click.mine', doIt);
$("#container").mousemove(showMouse);
$("#adiv").bind("acustom.atype", function () {
//console.log("custom");
});
});
</script>
</head>
<body>
<button id="doit">Do It</button>
<div id="container">
Hi
</div>
<div id="adiv">
</div>
</body>
</html>

Просмотреть файл

@ -1,23 +1,32 @@
<html id="html">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" dir="ltr" id="html">
<head>
<meta http-equiv="Content-Type" content="text/css; charset=utf-8" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery Test Suite</title>
<link rel="Stylesheet" media="screen" href="data/testsuite.css" />
<script>var jQuery = "jQuery", $ = "$"; // For testing .noConflict()</script>
<script type="text/javascript" src="../dist/jquery.js"></script>
<script type="text/javascript" src="data/testrunner.js"></script>
<script type="text/javascript" src="../src/jquery/coreTest.js"></script>
<script type="text/javascript" src="../src/selector/selectorTest.js"></script>
<script type="text/javascript" src="../src/event/eventTest.js"></script>
<script type="text/javascript" src="../src/fx/fxTest.js"></script>
<script type="text/javascript" src="unit/core.js"></script>
<script type="text/javascript" src="unit/dimensions.js"></script>
<script type="text/javascript" src="unit/selector.js"></script>
<script type="text/javascript" src="unit/event.js"></script>
<script type="text/javascript" src="unit/ajax.js"></script>
<script type="text/javascript" src="unit/fx.js"></script>
</head>
<body id="body">
<h1>jQuery Test Suite</h1>
<h1 id="header">jQuery Test Suite</h1>
<h2 id="banner"></h2>
<h2 id="userAgent"></h2>
<!-- Test HTML -->
<dl style="display:none;">
<div id="nothiddendiv" style="height:1px;background:white;">
<div id="nothiddendivchild"></div>
</div>
<!-- this iframe is outside the #main so it won't reload constantly wasting time, but it means the tests must be "safe" and clean up after themselves -->
<iframe id="loadediframe" name="loadediframe" style="display:none;" src="data/iframe.html"></iframe>
<dl id="dl" style="display:none;">
<div id="main" style="display: none;">
<p id="firstp">See <a id="simon1" href="http://simon.incutio.com/archive/2003/03/25/#getElementsBySelector" rel="bookmark">this blog entry</a> for more information.</p>
<p id="ap">
@ -37,13 +46,13 @@
<ul id="firstUL"></ul>
<ol id="empty"></ol>
<form id="form" action="formaction">
<input type="text" name="action" value="Test" id="text1"/>
<input type="text" name="action" value="Test" id="text1" maxlength="30"/>
<input type="text" name="text2" value="Test" id="text2" disabled="disabled"/>
<input type="radio" name="radio1" id="radio1"/>
<input type="radio" name="radio1" id="radio1" value="on"/>
<input type="radio" name="radio2" id="radio2" checked="checked"/>
<input type="checkbox" name="check" id="check1" checked="checked"/>
<input type="checkbox" id="check2"/>
<input type="checkbox" id="check2" value="on"/>
<input type="hidden" name="hidden" id="hidden1"/>
<input type="text" style="display:none;" name="foo[bar]" id="hidden2"/>
@ -52,22 +61,22 @@
<button id="button" name="button">Button</button>
<textarea id="area1">foobar</textarea>
<textarea id="area1" maxlength="30">foobar</textarea>
<select name="select1" id="select1">
<option id="option1a" value="">Nothing</option>
<option id="option1a" class="emptyopt" value="">Nothing</option>
<option id="option1b" value="1">1</option>
<option id="option1c" value="2">2</option>
<option id="option1d" value="3">3</option>
</select>
<select name="select2" id="select2">
<option id="option2a" value="">Nothing</option>
<option id="option2a" class="emptyopt" value="">Nothing</option>
<option id="option2b" value="1">1</option>
<option id="option2c" value="2">2</option>
<option id="option2d" selected="selected" value="3">3</option>
</select>
<select name="select3" id="select3" multiple="multiple">
<option id="option3a" value="">Nothing</option>
<option id="option3a" class="emptyopt" value="">Nothing</option>
<option id="option3b" selected="selected" value="1">1</option>
<option id="option3c" selected="selected" value="2">2</option>
<option id="option3d" value="3">3</option>
@ -90,10 +99,86 @@
<b id="floatTest">Float test.</b>
<iframe id="iframe" name="iframe"></iframe>
<form id="lengthtest">
<input type="text" id="length" name="test">
<input type="text" id="idTest" name="id">
<input type="text" id="length" name="test"/>
<input type="text" id="idTest" name="id"/>
</form>
<table id="table"></table>
<div id="fx-queue">
<div id="fadein" class='chain test'>fadeIn<div>fadeIn</div></div>
<div id="fadeout" class='chain test out'>fadeOut<div>fadeOut</div></div>
<div id="show" class='chain test'>show<div>show</div></div>
<div id="hide" class='chain test out'>hide<div>hide</div></div>
<div id="togglein" class='chain test'>togglein<div>togglein</div></div>
<div id="toggleout" class='chain test out'>toggleout<div>toggleout</div></div>
<div id="slideup" class='chain test'>slideUp<div>slideUp</div></div>
<div id="slidedown" class='chain test out'>slideDown<div>slideDown</div></div>
<div id="slidetogglein" class='chain test'>slideToggleIn<div>slideToggleIn</div></div>
<div id="slidetoggleout" class='chain test out'>slideToggleOut<div>slideToggleOut</div></div>
</div>
<div id="fx-tests"></div>
<form id="testForm" action="#" method="get">
<textarea name="T3" rows="2" cols="15">?
Z</textarea>
<input type="hidden" name="H1" value="x" />
<input type="hidden" name="H2" />
<input name="PWD" type="password" value="" />
<input name="T1" type="text" />
<input name="T2" type="text" value="YES" readonly="readonly" />
<input type="checkbox" name="C1" value="1" />
<input type="checkbox" name="C2" />
<input type="radio" name="R1" value="1" />
<input type="radio" name="R1" value="2" />
<input type="text" name="My Name" value="me" />
<input type="reset" name="reset" value="NO" />
<select name="S1">
<option value="abc">ABC</option>
<option value="abc">ABC</option>
<option value="abc">ABC</option>
</select>
<select name="S2" multiple="multiple" size="3">
<option value="abc">ABC</option>
<option value="abc">ABC</option>
<option value="abc">ABC</option>
</select>
<select name="S3">
<option selected="selected">YES</option>
</select>
<select name="S4">
<option value="" selected="selected">NO</option>
</select>
<input type="submit" name="sub1" value="NO" />
<input type="submit" name="sub2" value="NO" />
<input type="image" name="sub3" value="NO" />
<button name="sub4" type="submit" value="NO">NO</button>
<input name="D1" type="text" value="NO" disabled="disabled" />
<input type="checkbox" checked="checked" disabled="disabled" name="D2" value="NO" />
<input type="radio" name="D3" value="NO" checked="checked" disabled="disabled" />
<select name="D4" disabled="disabled">
<option selected="selected" value="NO">NO</option>
</select>
</form>
<div id="moretests">
<form>
<div id="checkedtest" style="display:none;">
<input type="radio" name="checkedtestradios" checked="checked"/>
<input type="radio" name="checkedtestradios" value="on"/>
<input type="checkbox" name="checkedtestcheckboxes" checked="checked"/>
<input type="checkbox" name="checkedtestcheckboxes" />
</div>
</form>
<div id="nonnodes"><span>hi</span> there <!-- mon ami --></div>
<div id="t2037">
<div><div class="hidden">hidden</div></div>
</div>
</div>
</div>
</dl>

Просмотреть файл

@ -0,0 +1,27 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" dir="ltr" id="html">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery Offset Test Suite</title>
<link rel="Stylesheet" media="screen" href="data/testsuite.css" />
<script type="text/javascript" src="../dist/jquery.js"></script>
<script type="text/javascript" src="data/testrunner.js"></script>
<script type="text/javascript" src="unit/offset.js"></script>
</head>
<body id="body">
<h1 id="header">jQuery Offset Test Suite</h1>
<h2 id="banner"></h2>
<h2 id="userAgent"></h2>
<!-- Test HTML -->
<div id="nothiddendiv" style="height:1px;background:white;"></div>
<dl id="dl" style="display:none;">
<div id="main" style="display: none;">
</div>
</dl>
<ol id="tests"></ol>
</body>
</html>

41
dom/tests/mochitest/ajax/jquery/test/test.js поставляемый Normal file
Просмотреть файл

@ -0,0 +1,41 @@
load( "build/js/writeFile.js", "build/js/parse.js" );
function addParams(name, params) {
if(params.length > 0) {
name += "(";
for ( var i = 0; i < params.length; i++) {
name += params[i].type + ", ";
}
return name.substring(0, name.length - 2) + ")";
} else {
return name + "()";
}
}
function addTestWrapper(name, test) {
return 'test("' + name + '", function() {\n' + test + '\n});';
}
var dir = arguments[1];
var jq = parse( read(arguments[0]) );
var testFile = [];
String.prototype.decode = function() {
return this.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
};
for ( var i = 0; i < jq.length; i++ ) {
if ( jq[i].tests.length > 0 ) {
var method = jq[i];
var name = addParams(method.name, method.params);
for(var j = 0; j < method.tests.length; j++) {
if(j > 0) {
name += "x";
}
testFile[testFile.length] = addTestWrapper(name, method.tests[j].decode()) + "\n";
}
}
}
var indexFile = readFile( "build/test/index.html" );
writeFile( dir + "/index.html", indexFile.replace( /{TESTS}/g, testFile.join("\n") ) );

Просмотреть файл

@ -39,7 +39,7 @@ DEPTH = ../../../../../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
relativesrcdir = dom/tests/mochitest/ajax/jquery/src/selector
relativesrcdir = dom/tests/mochitest/ajax/jquery/test/unit
include $(DEPTH)/config/autoconf.mk
@ -49,8 +49,13 @@ DIRS = \
include $(topsrcdir)/config/rules.mk
_TEST_FILES = \
ajax.js \
core.js \
dimensions.js \
event.js \
fx.js \
offset.js \
selector.js \
selectorTest.js \
$(NULL)
libs:: $(_TEST_FILES)

837
dom/tests/mochitest/ajax/jquery/test/unit/ajax.js поставляемый Normal file
Просмотреть файл

@ -0,0 +1,837 @@
module("ajax");
// Safari 3 randomly crashes when running these tests,
// but only in the full suite - you can run just the Ajax
// tests and they'll pass
//if ( !jQuery.browser.safari ) {
if ( !isLocal ) {
test("$.ajax() - success callbacks", function() {
expect( 8 );
$.ajaxSetup({ timeout: 0 });
stop();
setTimeout(function(){
$('#foo').ajaxStart(function(){
ok( true, "ajaxStart" );
}).ajaxStop(function(){
ok( true, "ajaxStop" );
start();
}).ajaxSend(function(){
ok( true, "ajaxSend" );
}).ajaxComplete(function(){
ok( true, "ajaxComplete" );
}).ajaxError(function(){
ok( false, "ajaxError" );
}).ajaxSuccess(function(){
ok( true, "ajaxSuccess" );
});
$.ajax({
url: url("data/name.html"),
beforeSend: function(){ ok(true, "beforeSend"); },
success: function(){ ok(true, "success"); },
error: function(){ ok(false, "error"); },
complete: function(){ ok(true, "complete"); }
});
}, 13);
});
/* mozilla: the ajaxSuccess part fails intermittently on MacOSX
test("$.ajax() - error callbacks", function() {
expect( 7 );
stop();
$('#foo').ajaxStart(function(){
ok( true, "ajaxStart" );
}).ajaxStop(function(){
ok( true, "ajaxStop" );
start();
}).ajaxSend(function(){
ok( true, "ajaxSend" );
}).ajaxComplete(function(){
ok( true, "ajaxComplete" );
}).ajaxError(function(){
ok( true, "ajaxError" );
}).ajaxSuccess(function(){
ok( false, "ajaxSuccess" );
})
;
$.ajaxSetup({ timeout: 500 });
$.ajax({
url: url("data/name.php?wait=5"),
beforeSend: function(){ ok(true, "beforeSend"); },
success: function(){ ok(false, "success"); },
error: function(){ ok(true, "error"); },
complete: function(){ ok(true, "complete"); }
});
});
*/
test("$.ajax() - disabled globals", function() {
expect( 3 );
stop();
$('#foo').ajaxStart(function(){
ok( false, "ajaxStart" );
}).ajaxStop(function(){
ok( false, "ajaxStop" );
}).ajaxSend(function(){
ok( false, "ajaxSend" );
}).ajaxComplete(function(){
ok( false, "ajaxComplete" );
}).ajaxError(function(){
ok( false, "ajaxError" );
}).ajaxSuccess(function(){
ok( false, "ajaxSuccess" );
});
$.ajax({
global: false,
url: url("data/name.html"),
beforeSend: function(){ ok(true, "beforeSend"); },
success: function(){ ok(true, "success"); },
error: function(){ ok(false, "error"); },
complete: function(){
ok(true, "complete");
setTimeout(function(){ start(); }, 13);
}
});
});
test("$.ajax - xml: non-namespace elements inside namespaced elements", function() {
expect(3);
stop();
$.ajax({
url: url("data/with_fries.xml"),
dataType: "xml",
success: function(resp) {
equals( $("properties", resp).length, 1, 'properties in responseXML' );
equals( $("jsconf", resp).length, 1, 'jsconf in responseXML' );
equals( $("thing", resp).length, 2, 'things in responseXML' );
start();
}
});
});
test("$.ajax - beforeSend", function() {
expect(1);
stop();
var check = false;
$.ajaxSetup({ timeout: 0 });
$.ajax({
url: url("data/name.html"),
beforeSend: function(xml) {
check = true;
},
success: function(data) {
ok( check, "check beforeSend was executed" );
start();
}
});
});
test("$.ajax - beforeSend, cancel request (#2688)", function() {
expect(2);
var request = $.ajax({
url: url("data/name.html"),
beforeSend: function() {
ok( true, "beforeSend got called, canceling" );
return false;
},
success: function() {
ok( false, "request didn't get canceled" );
},
complete: function() {
ok( false, "request didn't get canceled" );
},
error: function() {
ok( false, "request didn't get canceled" );
}
});
ok( request === false, "canceled request must return false instead of XMLHttpRequest instance" );
});
var foobar;
test("$.ajax - dataType html", function() {
expect(5);
stop();
foobar = null;
testFoo = undefined;
var verifyEvaluation = function() {
equals( testFoo, "foo", 'Check if script was evaluated for datatype html' );
equals( foobar, "bar", 'Check if script src was evaluated for datatype html' );
start();
};
$.ajax({
dataType: "html",
url: url("data/test.html"),
success: function(data) {
$("#ap").html(data);
ok( data.match(/^html text/), 'Check content for datatype html' );
setTimeout(verifyEvaluation, 600);
}
});
});
test("serialize()", function() {
expect(6);
equals( $('#form').serialize(),
"action=Test&radio2=on&check=on&hidden=&foo%5Bbar%5D=&name=name&select1=&select2=3&select3=1&select3=2",
'Check form serialization as query string');
equals( $('#form :input').serialize(),
"action=Test&radio2=on&check=on&hidden=&foo%5Bbar%5D=&name=name&select1=&select2=3&select3=1&select3=2",
'Check input serialization as query string');
equals( $('#testForm').serialize(),
'T3=%3F%0AZ&H1=x&H2=&PWD=&T1=&T2=YES&My+Name=me&S1=abc&S3=YES&S4=',
'Check form serialization as query string');
equals( $('#testForm :input').serialize(),
'T3=%3F%0AZ&H1=x&H2=&PWD=&T1=&T2=YES&My+Name=me&S1=abc&S3=YES&S4=',
'Check input serialization as query string');
equals( $('#form, #testForm').serialize(),
"action=Test&radio2=on&check=on&hidden=&foo%5Bbar%5D=&name=name&select1=&select2=3&select3=1&select3=2&T3=%3F%0AZ&H1=x&H2=&PWD=&T1=&T2=YES&My+Name=me&S1=abc&S3=YES&S4=",
'Multiple form serialization as query string');
equals( $('#form, #testForm :input').serialize(),
"action=Test&radio2=on&check=on&hidden=&foo%5Bbar%5D=&name=name&select1=&select2=3&select3=1&select3=2&T3=%3F%0AZ&H1=x&H2=&PWD=&T1=&T2=YES&My+Name=me&S1=abc&S3=YES&S4=",
'Mixed form/input serialization as query string');
});
test("$.param()", function() {
expect(4);
var params = {foo:"bar", baz:42, quux:"All your base are belong to us"};
equals( $.param(params), "foo=bar&baz=42&quux=All+your+base+are+belong+to+us", "simple" );
params = {someName: [1, 2, 3], regularThing: "blah" };
equals( $.param(params), "someName=1&someName=2&someName=3&regularThing=blah", "with array" );
params = {"foo[]":["baz", 42, "All your base are belong to us"]};
equals( $.param(params), "foo%5B%5D=baz&foo%5B%5D=42&foo%5B%5D=All+your+base+are+belong+to+us", "more array" );
params = {"foo[bar]":"baz", "foo[beep]":42, "foo[quux]":"All your base are belong to us"};
equals( $.param(params), "foo%5Bbar%5D=baz&foo%5Bbeep%5D=42&foo%5Bquux%5D=All+your+base+are+belong+to+us", "even more arrays" );
});
test("synchronous request", function() {
expect(1);
ok( /^{ "data"/.test( $.ajax({url: url("data/json_obj.js"), async: false}).responseText ), "check returned text" );
});
test("synchronous request with callbacks", function() {
expect(2);
var result;
$.ajax({url: url("data/json_obj.js"), async: false, success: function(data) { ok(true, "sucess callback executed"); result = data; } });
ok( /^{ "data"/.test( result ), "check returned text" );
});
test("pass-through request object", function() {
expect(8);
stop(true);
var target = "data/name.html";
var successCount = 0;
var errorCount = 0;
var errorEx = "";
var success = function() {
successCount++;
};
$("#foo").ajaxError(function (e, xml, s, ex) {
errorCount++;
errorEx += ": " + xml.status;
});
$("#foo").one('ajaxStop', function () {
equals(successCount, 5, "Check all ajax calls successful");
equals(errorCount, 0, "Check no ajax errors (status" + errorEx + ")");
$("#foo").unbind('ajaxError');
start();
});
ok( $.get(url(target), success), "get" );
ok( $.post(url(target), success), "post" );
ok( $.getScript(url("data/test.js"), success), "script" );
ok( $.getJSON(url("data/json_obj.js"), success), "json" );
ok( $.ajax({url: url(target), success: success}), "generic" );
});
/* mozilla: php not currently supported in mochitest (08/08/2008)
test("ajax cache", function () {
expect(18);
stop();
var count = 0;
$("#firstp").bind("ajaxSuccess", function (e, xml, s) {
var re = /_=(.*?)(&|$)/g;
var oldOne = null;
for (var i = 0; i < 6; i++) {
var ret = re.exec(s.url);
if (!ret) {
break;
}
oldOne = ret[1];
}
equals(i, 1, "Test to make sure only one 'no-cache' parameter is there");
ok(oldOne != "tobereplaced555", "Test to be sure parameter (if it was there) was replaced");
if(++count == 6)
start();
});
ok( $.ajax({url: "data/text.php", cache:false}), "test with no parameters" );
ok( $.ajax({url: "data/text.php?pizza=true", cache:false}), "test with 1 parameter" );
ok( $.ajax({url: "data/text.php?_=tobereplaced555", cache:false}), "test with _= parameter" );
ok( $.ajax({url: "data/text.php?pizza=true&_=tobereplaced555", cache:false}), "test with 1 parameter plus _= one" );
ok( $.ajax({url: "data/text.php?_=tobereplaced555&tv=false", cache:false}), "test with 1 parameter plus _= one before it" );
ok( $.ajax({url: "data/text.php?name=David&_=tobereplaced555&washere=true", cache:false}), "test with 2 parameters surrounding _= one" );
});
*/
test("global ajaxSettings", function() {
expect(2);
var tmp = jQuery.extend({}, jQuery.ajaxSettings);
var orig = { url: "data/with_fries.xml" };
var t;
$.ajaxSetup({ data: {foo: 'bar', bar: 'BAR'} });
t = jQuery.extend({}, orig);
t.data = {};
$.ajax(t);
ok( t.url.indexOf('foo') > -1 && t.url.indexOf('bar') > -1, "Check extending {}" );
t = jQuery.extend({}, orig);
t.data = { zoo: 'a', ping: 'b' };
$.ajax(t);
ok( t.url.indexOf('ping') > -1 && t.url.indexOf('zoo') > -1 && t.url.indexOf('foo') > -1 && t.url.indexOf('bar') > -1, "Check extending { zoo: 'a', ping: 'b' }" );
jQuery.ajaxSettings = tmp;
});
test("load(String)", function() {
expect(1);
stop(true); // check if load can be called with only url
$('#first').load("data/name.html", start);
});
test("load('url selector')", function() {
expect(1);
stop(true); // check if load can be called with only url
$('#first').load("data/test3.html div.user", function(){
equals( $(this).children("div").length, 2, "Verify that specific elements were injected" );
start();
});
});
test("load(String, Function) with ajaxSetup on dataType json, see #2046", function() {
expect(1);
stop();
$.ajaxSetup({ dataType: "json" });
$("#first").ajaxComplete(function (e, xml, s) {
equals( s.dataType, "html", "Verify the load() dataType was html" );
$("#first").unbind("ajaxComplete");
$.ajaxSetup({ dataType: "" });
start();
});
$('#first').load("data/test3.html");
});
test("load(String, Function) - simple: inject text into DOM", function() {
expect(2);
stop();
$('#first').load(url("data/name.html"), function() {
ok( /^ERROR/.test($('#first').text()), 'Check if content was injected into the DOM' );
start();
});
});
test("load(String, Function) - check scripts", function() {
expect(7);
stop();
window.testFoo = undefined;
window.foobar = null;
var verifyEvaluation = function() {
equals( foobar, "bar", 'Check if script src was evaluated after load' );
equals( $('#ap').html(), 'bar', 'Check if script evaluation has modified DOM');
start();
};
$('#first').load(url('data/test.html'), function() {
ok( $('#first').html().match(/^html text/), 'Check content after loading html' );
equals( $('#foo').html(), 'foo', 'Check if script evaluation has modified DOM');
equals( testFoo, "foo", 'Check if script was evaluated after load' );
setTimeout(verifyEvaluation, 600);
});
});
test("load(String, Function) - check file with only a script tag", function() {
expect(3);
stop();
testFoo = undefined;
$('#first').load(url('data/test2.html'), function() {
equals( $('#foo').html(), 'foo', 'Check if script evaluation has modified DOM');
equals( testFoo, "foo", 'Check if script was evaluated after load' );
start();
});
});
test("$.get(String, Hash, Function) - parse xml and use text() on nodes", function() {
expect(2);
stop();
$.get(url('data/dashboard.xml'), function(xml) {
var content = [];
$('tab', xml).each(function() {
content.push($(this).text());
});
equals( content[0], 'blabla', 'Check first tab');
equals( content[1], 'blublu', 'Check second tab');
start();
});
});
test("$.getScript(String, Function) - with callback", function() {
expect(2);
stop();
window.foobar = null;
$.getScript(url("data/test.js"), function() {
equals( foobar, "bar", 'Check if script was evaluated' );
setTimeout(start, 100);
});
});
test("$.getScript(String, Function) - no callback", function() {
expect(1);
stop(true);
$.getScript(url("data/test.js"), start);
});
/* mozilla: Tests using php scripts not currently supported (06/26/2008)
test("$.ajax() - JSONP, Local", function() {
expect(7);
var count = 0;
function plus(){ if ( ++count == 7 ) start(); }
stop();
$.ajax({
url: "data/jsonp.php",
dataType: "jsonp",
success: function(data){
ok( data.data, "JSON results returned (GET, no callback)" );
plus();
},
error: function(data){
ok( false, "Ajax error JSON (GET, no callback)" );
plus();
}
});
$.ajax({
url: "data/jsonp.php?callback=?",
dataType: "jsonp",
success: function(data){
ok( data.data, "JSON results returned (GET, url callback)" );
plus();
},
error: function(data){
ok( false, "Ajax error JSON (GET, url callback)" );
plus();
}
});
$.ajax({
url: "data/jsonp.php",
dataType: "jsonp",
data: "callback=?",
success: function(data){
ok( data.data, "JSON results returned (GET, data callback)" );
plus();
},
error: function(data){
ok( false, "Ajax error JSON (GET, data callback)" );
plus();
}
});
$.ajax({
url: "data/jsonp.php",
dataType: "jsonp",
jsonp: "callback",
success: function(data){
ok( data.data, "JSON results returned (GET, data obj callback)" );
plus();
},
error: function(data){
ok( false, "Ajax error JSON (GET, data obj callback)" );
plus();
}
});
$.ajax({
type: "POST",
url: "data/jsonp.php",
dataType: "jsonp",
success: function(data){
ok( data.data, "JSON results returned (POST, no callback)" );
plus();
},
error: function(data){
ok( false, "Ajax error JSON (GET, data obj callback)" );
plus();
}
});
$.ajax({
type: "POST",
url: "data/jsonp.php",
data: "callback=?",
dataType: "jsonp",
success: function(data){
ok( data.data, "JSON results returned (POST, data callback)" );
plus();
},
error: function(data){
ok( false, "Ajax error JSON (POST, data callback)" );
plus();
}
});
$.ajax({
type: "POST",
url: "data/jsonp.php",
jsonp: "callback",
dataType: "jsonp",
success: function(data){
ok( data.data, "JSON results returned (POST, data obj callback)" );
plus();
},
error: function(data){
ok( false, "Ajax error JSON (POST, data obj callback)" );
plus();
}
});
});
test("$.ajax() - JSONP, Remote", function() {
expect(4);
var count = 0;
function plus(){ if ( ++count == 4 ) start(); }
var base = window.location.href.replace(/\?.*$/, "");
stop();
$.ajax({
url: base + "data/jsonp.php",
dataType: "jsonp",
success: function(data){
ok( data.data, "JSON results returned (GET, no callback)" );
plus();
},
error: function(data){
ok( false, "Ajax error JSON (GET, no callback)" );
plus();
}
});
$.ajax({
url: base + "data/jsonp.php?callback=?",
dataType: "jsonp",
success: function(data){
ok( data.data, "JSON results returned (GET, url callback)" );
plus();
},
error: function(data){
ok( false, "Ajax error JSON (GET, url callback)" );
plus();
}
});
$.ajax({
url: base + "data/jsonp.php",
dataType: "jsonp",
data: "callback=?",
success: function(data){
ok( data.data, "JSON results returned (GET, data callback)" );
plus();
},
error: function(data){
ok( false, "Ajax error JSON (GET, data callback)" );
plus();
}
});
$.ajax({
url: base + "data/jsonp.php",
dataType: "jsonp",
jsonp: "callback",
success: function(data){
ok( data.data, "JSON results returned (GET, data obj callback)" );
plus();
},
error: function(data){
ok( false, "Ajax error JSON (GET, data obj callback)" );
plus();
}
});
});
test("$.ajax() - script, Remote", function() {
expect(2);
var base = window.location.href.replace(/\?.*$/, "");
stop();
window.foobar = null;
$.ajax({
url: base + "data/test.js",
dataType: "script",
success: function(data){
ok( foobar, "Script results returned (GET, no callback)" );
start();
}
});
});
test("$.ajax() - script, Remote with POST", function() {
expect(3);
var base = window.location.href.replace(/\?.*$/, "");
stop();
window.foobar = null;
$.ajax({
url: base + "data/test.js",
type: "POST",
dataType: "script",
success: function(data, status){
ok( foobar, "Script results returned (GET, no callback)" );
equals( status, "success", "Script results returned (GET, no callback)" );
start();
}
});
});
test("$.ajax() - script, Remote with scheme-less URL", function() {
expect(2);
var base = window.location.href.replace(/\?.*$/, "");
base = base.replace(/^.*?\/\//, "//");
stop();
window.foobar = null;
$.ajax({
url: base + "data/test.js",
dataType: "script",
success: function(data){
ok( foobar, "Script results returned (GET, no callback)" );
start();
}
});
});
test("$.getJSON(String, Hash, Function) - JSON array", function() {
expect(4);
stop();
$.getJSON(url("data/json.php"), {json: "array"}, function(json) {
equals( json[0].name, 'John', 'Check JSON: first, name' );
equals( json[0].age, 21, 'Check JSON: first, age' );
equals( json[1].name, 'Peter', 'Check JSON: second, name' );
equals( json[1].age, 25, 'Check JSON: second, age' );
start();
});
});
test("$.getJSON(String, Function) - JSON object", function() {
expect(2);
stop();
$.getJSON(url("data/json.php"), function(json) {
equals( json.data.lang, 'en', 'Check JSON: lang' );
equals( json.data.length, 25, 'Check JSON: length' );
start();
});
});
test("$.getJSON(String, Function) - JSON object with absolute url to local content", function() {
expect(2);
var base = window.location.href.replace(/\?.*$/, "");
stop();
$.getJSON(url(base + "data/json.php"), function(json) {
equals( json.data.lang, 'en', 'Check JSON: lang' );
equals( json.data.length, 25, 'Check JSON: length' );
start();
});
});
test("$.post(String, Hash, Function) - simple with xml", function() {
expect(4);
stop();
$.post(url("data/name.php"), {xml: "5-2"}, function(xml){
$('math', xml).each(function() {
equals( $('calculation', this).text(), '5-2', 'Check for XML' );
equals( $('result', this).text(), '3', 'Check for XML' );
});
});
$.post(url("data/name.php?xml=5-2"), {}, function(xml){
$('math', xml).each(function() {
equals( $('calculation', this).text(), '5-2', 'Check for XML' );
equals( $('result', this).text(), '3', 'Check for XML' );
});
start();
});
});
test("$.ajaxSetup({timeout: Number}) - with global timeout", function() {
stop();
var passed = 0;
$.ajaxSetup({timeout: 1000});
var pass = function() {
passed++;
if ( passed == 2 ) {
ok( true, 'Check local and global callbacks after timeout' );
$('#main').unbind("ajaxError");
start();
}
};
var fail = function(a,b,c) {
ok( false, 'Check for timeout failed ' + a + ' ' + b );
start();
};
$('#main').ajaxError(pass);
$.ajax({
type: "GET",
url: url("data/name.php?wait=5"),
error: pass,
success: fail
});
// reset timeout
$.ajaxSetup({timeout: 0});
});
test("$.ajaxSetup({timeout: Number}) with localtimeout", function() {
stop();
$.ajaxSetup({timeout: 50});
$.ajax({
type: "GET",
timeout: 5000,
url: url("data/name.php?wait=1"),
error: function() {
ok( false, 'Check for local timeout failed' );
start();
},
success: function() {
ok( true, 'Check for local timeout' );
start();
}
});
// reset timeout
$.ajaxSetup({timeout: 0});
});
test("$.ajax - simple get", function() {
expect(1);
stop();
$.ajax({
type: "GET",
url: url("data/name.php?name=foo"),
success: function(msg){
equals( msg, 'bar', 'Check for GET' );
start();
}
});
});
test("$.ajax - simple post", function() {
expect(1);
stop();
$.ajax({
type: "POST",
url: url("data/name.php"),
data: "name=peter",
success: function(msg){
equals( msg, 'pan', 'Check for POST' );
start();
}
});
});
test("ajaxSetup()", function() {
expect(1);
stop();
$.ajaxSetup({
url: url("data/name.php?name=foo"),
success: function(msg){
equals( msg, 'bar', 'Check for GET' );
start();
}
});
$.ajax();
});
test("custom timeout does not set error message when timeout occurs, see #970", function() {
stop();
$.ajax({
url: "data/name.php?wait=10",
timeout: 500,
error: function(request, status) {
ok( status != null, "status shouldn't be null in error handler" );
equals( "timeout", status );
start();
}
});
});
test("data option: evaluate function values (#2806)", function() {
stop();
$.ajax({
url: "data/echoQuery.php",
data: {
key: function() {
return "value";
}
},
success: function(result) {
equals( result, "key=value" );
start();
}
})
});
*/
}
//}

1693
dom/tests/mochitest/ajax/jquery/test/unit/core.js поставляемый Normal file

Разница между файлами не показана из-за своего большого размера Загрузить разницу

86
dom/tests/mochitest/ajax/jquery/test/unit/dimensions.js поставляемый Normal file
Просмотреть файл

@ -0,0 +1,86 @@
module("dimensions");
test("innerWidth()", function() {
expect(3);
var $div = $("#nothiddendiv");
// set styles
$div.css({
margin: 10,
border: "2px solid #fff",
width: 30
});
equals($div.innerWidth(), 30, "Test with margin and border");
$div.css("padding", "20px");
equals($div.innerWidth(), 70, "Test with margin, border and padding");
$div.hide();
equals($div.innerWidth(), 70, "Test hidden div");
// reset styles
$div.css({ display: "", border: "", padding: "", width: "", height: "" });
});
test("innerHeight()", function() {
expect(3);
var $div = $("#nothiddendiv");
// set styles
$div.css({
margin: 10,
border: "2px solid #fff",
height: 30
});
equals($div.innerHeight(), 30, "Test with margin and border");
$div.css("padding", "20px");
equals($div.innerHeight(), 70, "Test with margin, border and padding");
$div.hide();
equals($div.innerHeight(), 70, "Test hidden div");
// reset styles
$div.css({ display: "", border: "", padding: "", width: "", height: "" });
});
test("outerWidth()", function() {
expect(6);
var $div = $("#nothiddendiv");
$div.css("width", 30);
equals($div.outerWidth(), 30, "Test with only width set");
$div.css("padding", "20px");
equals($div.outerWidth(), 70, "Test with padding");
$div.css("border", "2px solid #fff");
equals($div.outerWidth(), 74, "Test with padding and border");
$div.css("margin", "10px");
equals($div.outerWidth(), 74, "Test with padding, border and margin without margin option");
$div.css("position", "absolute");
equals($div.outerWidth(true), 94, "Test with padding, border and margin with margin option");
$div.hide();
equals($div.outerWidth(true), 94, "Test hidden div with padding, border and margin with margin option");
// reset styles
$div.css({ position: "", display: "", border: "", padding: "", width: "", height: "" });
});
test("outerHeight()", function() {
expect(6);
var $div = $("#nothiddendiv");
$div.css("height", 30);
equals($div.outerHeight(), 30, "Test with only width set");
$div.css("padding", "20px");
equals($div.outerHeight(), 70, "Test with padding");
$div.css("border", "2px solid #fff");
equals($div.outerHeight(), 74, "Test with padding and border");
$div.css("margin", "10px");
equals($div.outerHeight(), 74, "Test with padding, border and margin without margin option");
equals($div.outerHeight(true), 94, "Test with padding, border and margin with margin option");
$div.hide();
equals($div.outerHeight(true), 94, "Test hidden div with padding, border and margin with margin option");
// reset styles
$div.css({ display: "", border: "", padding: "", width: "", height: "" });
});

348
dom/tests/mochitest/ajax/jquery/test/unit/event.js поставляемый Normal file
Просмотреть файл

@ -0,0 +1,348 @@
module("event");
test("bind(), with data", function() {
expect(3);
var handler = function(event) {
ok( event.data, "bind() with data, check passed data exists" );
equals( event.data.foo, "bar", "bind() with data, Check value of passed data" );
};
$("#firstp").bind("click", {foo: "bar"}, handler).click().unbind("click", handler);
ok( !jQuery.data($("#firstp")[0], "events"), "Event handler unbound when using data." );
});
test("bind(), with data, trigger with data", function() {
expect(4);
var handler = function(event, data) {
ok( event.data, "check passed data exists" );
equals( event.data.foo, "bar", "Check value of passed data" );
ok( data, "Check trigger data" );
equals( data.bar, "foo", "Check value of trigger data" );
};
$("#firstp").bind("click", {foo: "bar"}, handler).trigger("click", [{bar: "foo"}]).unbind("click", handler);
});
test("bind(), multiple events at once", function() {
expect(2);
var clickCounter = 0,
mouseoverCounter = 0;
var handler = function(event) {
if (event.type == "click")
clickCounter += 1;
else if (event.type == "mouseover")
mouseoverCounter += 1;
};
$("#firstp").bind("click mouseover", handler).trigger("click").trigger("mouseover");
equals( clickCounter, 1, "bind() with multiple events at once" );
equals( mouseoverCounter, 1, "bind() with multiple events at once" );
});
test("bind(), no data", function() {
expect(1);
var handler = function(event) {
ok ( !event.data, "Check that no data is added to the event object" );
};
$("#firstp").bind("click", handler).trigger("click");
});
test("bind(), iframes", function() {
// events don't work with iframes, see #939 - this test fails in IE because of contentDocument
// var doc = document.getElementById("iframe").contentDocument;
//
// doc.body.innerHTML = "<input type='text'/>";
//
// var input = doc.getElementsByTagName("input")[0];
//
// $(input).bind("click",function() {
// ok( true, "Binding to element inside iframe" );
// }).click();
});
test("bind(), trigger change on select", function() {
expect(3);
var counter = 0;
function selectOnChange(event) {
equals( event.data, counter++, "Event.data is not a global event object" );
};
$("#form select").each(function(i){
$(this).bind('change', i, selectOnChange);
}).trigger('change');
});
test("bind(), namespaced events, cloned events", function() {
expect(6);
$("#firstp").bind("custom.test",function(e){
ok(true, "Custom event triggered");
});
$("#firstp").bind("click",function(e){
ok(true, "Normal click triggered");
});
$("#firstp").bind("click.test",function(e){
ok(true, "Namespaced click triggered");
});
// Trigger both bound fn (2)
$("#firstp").trigger("click");
// Trigger one bound fn (1)
$("#firstp").trigger("click.test");
// Remove only the one fn
$("#firstp").unbind("click.test");
// Trigger the remaining fn (1)
$("#firstp").trigger("click");
// Remove the remaining fn
$("#firstp").unbind(".test");
// Trigger the remaining fn (0)
$("#firstp").trigger("custom");
// using contents will get comments regular, text, and comment nodes
$("#nonnodes").contents().bind("tester", function () {
equals(this.nodeType, 1, "Check node,textnode,comment bind just does real nodes" );
}).trigger("tester");
// Make sure events stick with appendTo'd elements (which are cloned) #2027
$("<a href='#fail' class='test'>test</a>").click(function(){ return false; }).appendTo("p");
ok( $("a.test:first").triggerHandler("click") === false, "Handler is bound to appendTo'd elements" );
});
test("trigger() shortcuts", function() {
expect(6);
$('<li><a href="#">Change location</a></li>').prependTo('#firstUL').find('a').bind('click', function() {
var close = $('spanx', this); // same with $(this).find('span');
equals( close.length, 0, "Context element does not exist, length must be zero" );
ok( !close[0], "Context element does not exist, direct access to element must return undefined" );
return false;
}).click();
$("#check1").click(function() {
ok( true, "click event handler for checkbox gets fired twice, see #815" );
}).click();
var counter = 0;
$('#firstp')[0].onclick = function(event) {
counter++;
};
$('#firstp').click();
equals( counter, 1, "Check that click, triggers onclick event handler also" );
var clickCounter = 0;
$('#simon1')[0].onclick = function(event) {
clickCounter++;
};
$('#simon1').click();
equals( clickCounter, 1, "Check that click, triggers onclick event handler on an a tag also" );
$('<img />').load(function(){
ok( true, "Trigger the load event, using the shortcut .load() (#2819)");
}).load();
});
test("unbind(event)", function() {
expect(8);
var el = $("#firstp");
el.click(function() {
ok( true, "Fake normal bind" );
});
el.click(function(event) {
el.unbind(event);
ok( true, "Fake onebind" );
});
el.click().click();
el.click(function() { return; });
el.unbind('click');
ok( !el[0].onclick, "Handler is removed" ); // Bug #964
el.click(function() { return; });
el.unbind('change',function(){ return; });
for (var ret in jQuery.data(el[0], "events")['click']) break;
ok( ret, "Extra handlers weren't accidentally removed." );
el.unbind('click');
ok( !jQuery.data(el[0], "events"), "Removed the events expando after all handlers are unbound." );
reset();
var clickCounter = (mouseoverCounter = 0);
var handler = function(event) {
if (event.type == "click")
clickCounter += 1;
else if (event.type == "mouseover")
mouseoverCounter += 1;
};
$("#firstp").bind("click mouseover", handler).unbind("click mouseover", handler).trigger("click").trigger("mouseover");
equals( clickCounter, 0, "unbind() with multiple events at once" );
equals( mouseoverCounter, 0, "unbind() with multiple events at once" );
});
test("trigger(event, [data], [fn])", function() {
expect(67);
var handler = function(event, a, b, c) {
equals( event.type, "click", "check passed data" );
equals( a, 1, "check passed data" );
equals( b, "2", "check passed data" );
equals( c, "abc", "check passed data" );
return "test";
};
var handler2 = function(a, b, c) {
equals( a, 1, "check passed data" );
equals( b, "2", "check passed data" );
equals( c, "abc", "check passed data" );
return false;
};
var handler3 = function(a, b, c, v) {
equals( a, 1, "check passed data" );
equals( b, "2", "check passed data" );
equals( c, "abc", "check passed data" );
equals( v, "test", "check current value" );
return "newVal";
};
var handler4 = function(a, b, c, v) {
equals( a, 1, "check passed data" );
equals( b, "2", "check passed data" );
equals( c, "abc", "check passed data" );
equals( v, "test", "check current value" );
};
// Simulate a "native" click
$("#firstp")[0].click = function(){
ok( true, "Native call was triggered" );
};
// Triggers handlrs and native
// Trigger 5
$("#firstp").bind("click", handler).trigger("click", [1, "2", "abc"]);
// Triggers handlers, native, and extra fn
// Triggers 9
$("#firstp").trigger("click", [1, "2", "abc"], handler4);
// Simulate a "native" click
$("#firstp")[0].click = function(){
ok( false, "Native call was triggered" );
};
// Triggers handlers, native, and extra fn
// Triggers 7
$("#firstp").trigger("click", [1, "2", "abc"], handler2);
// Trigger only the handlers (no native)
// Triggers 5
equals( $("#firstp").triggerHandler("click", [1, "2", "abc"]), "test", "Verify handler response" );
// Trigger only the handlers (no native) and extra fn
// Triggers 8
equals( $("#firstp").triggerHandler("click", [1, "2", "abc"], handler2), false, "Verify handler response" );
// Build fake click event to pass in
var eventObj = jQuery.event.fix({ type: "foo", target: document.body });
// Trigger only the handlers (no native), with external event obj
// Triggers 5
equals( $("#firstp").triggerHandler("click", [eventObj, 1, "2", "abc"]), "test", "Verify handler response" );
// Trigger only the handlers (no native) and extra fn, with external event obj
// Triggers 9
eventObj = jQuery.event.fix({ type: "foo", target: document.body });
equals( $("#firstp").triggerHandler("click", [eventObj, 1, "2", "abc"], handler), "test", "Verify handler response" );
var pass = true;
try {
$('input:first')
.hide()
.trigger('focus');
} catch(e) {
pass = false;
}
ok( pass, "Trigger focus on hidden element" );
// have the extra handler override the return
// Triggers 9
equals( $("#firstp").triggerHandler("click", [1, "2", "abc"], handler3), "newVal", "Verify triggerHandler return is overwritten by extra function" );
// have the extra handler leave the return value alone
// Triggers 9
equals( $("#firstp").triggerHandler("click", [1, "2", "abc"], handler4), "test", "Verify triggerHandler return is not overwritten by extra function" );
});
test("toggle(Function, Function, ...)", function() {
expect(11);
var count = 0,
fn1 = function(e) { count++; },
fn2 = function(e) { count--; },
preventDefault = function(e) { e.preventDefault() },
link = $('#mark');
link.click(preventDefault).click().toggle(fn1, fn2).click().click().click().click().click();
equals( count, 1, "Check for toggle(fn, fn)" );
$("#firstp").toggle(function () {
equals(arguments.length, 4, "toggle correctly passes through additional triggered arguments, see #1701" )
}, function() {}).trigger("click", [ 1, 2, 3 ]);
var first = 0;
$("#simon1").one("click", function() {
ok( true, "Execute event only once" );
$(this).toggle(function() {
equals( first++, 0, "toggle(Function,Function) assigned from within one('xxx'), see #1054" );
}, function() {
equals( first, 1, "toggle(Function,Function) assigned from within one('xxx'), see #1054" );
});
return false;
}).click().click().click();
var turn = 0;
var fns = [
function(){
turn = 1;
},
function(){
turn = 2;
},
function(){
turn = 3;
}
];
var $div = $("<div>&nbsp;</div>").toggle( fns[0], fns[1], fns[2] );
$div.click();
equals( turn, 1, "Trying toggle with 3 functions, attempt 1 yields 1");
$div.click();
equals( turn, 2, "Trying toggle with 3 functions, attempt 2 yields 2");
$div.click();
equals( turn, 3, "Trying toggle with 3 functions, attempt 3 yields 3");
$div.click();
equals( turn, 1, "Trying toggle with 3 functions, attempt 4 yields 1");
$div.click();
equals( turn, 2, "Trying toggle with 3 functions, attempt 5 yields 2");
$div.unbind('click',fns[0]);
var data = $.data( $div[0], 'events' );
ok( !data, "Unbinding one function from toggle unbinds them all");
});
test("jQuery(function($) {})", function() {
stop();
jQuery(function($) {
equals(jQuery, $, "ready doesn't provide an event object, instead it provides a reference to the jQuery function, see http://docs.jquery.com/Events/ready#fn");
start();
});
});
test("event properties", function() {
stop();
$("#simon1").click(function(event) {
ok( event.timeStamp, "assert event.timeStamp is present" );
start();
}).click();
});

427
dom/tests/mochitest/ajax/jquery/test/unit/fx.js поставляемый Normal file
Просмотреть файл

@ -0,0 +1,427 @@
module("fx");
test("animate(Hash, Object, Function)", function() {
expect(1);
stop();
var hash = {opacity: 'show'};
var hashCopy = $.extend({}, hash);
$('#foo').animate(hash, 0, function() {
equals( hash.opacity, hashCopy.opacity, 'Check if animate changed the hash parameter' );
start();
});
});
test("animate option (queue === false)", function () {
expect(1);
stop();
var order = [];
var $foo = $("#foo");
$foo.animate({width:'100px'}, 200, function () {
// should finish after unqueued animation so second
order.push(2);
});
$foo.animate({fontSize:'2em'}, {queue:false, duration:10, complete:function () {
// short duration and out of queue so should finish first
order.push(1);
}});
$foo.animate({height:'100px'}, 10, function() {
// queued behind the first animation so should finish third
order.push(3);
isSet( order, [ 1, 2, 3], "Animations finished in the correct order" );
start();
});
});
test("queue() defaults to 'fx' type", function () {
expect(2);
stop();
var $foo = $("#foo");
$foo.queue("fx", [ "sample", "array" ]);
var arr = $foo.queue();
isSet(arr, [ "sample", "array" ], "queue() got an array set with type 'fx'");
$foo.queue([ "another", "one" ]);
var arr = $foo.queue("fx");
isSet(arr, [ "another", "one" ], "queue('fx') got an array set with no type");
// clean up after test
$foo.queue([]);
start();
});
test("stop()", function() {
expect(3);
stop();
var $foo = $("#nothiddendiv");
var w = 0;
$foo.hide().width(200).width();
$foo.animate({ width:'show' }, 1000);
setTimeout(function(){
var nw = $foo.width();
ok( nw != w, "An animation occurred " + nw + "px " + w + "px");
$foo.stop();
nw = $foo.width();
ok( nw != w, "Stop didn't reset the animation " + nw + "px " + w + "px");
setTimeout(function(){
equals( nw, $foo.width(), "The animation didn't continue" );
start();
}, 100);
}, 100);
});
test("stop() - several in queue", function() {
expect(4);
stop();
var $foo = $("#nothiddendiv");
var w = 0;
$foo.hide().width(200).width();
$foo.animate({ width:'show' }, 1000);
$foo.animate({ width:'hide' }, 1000);
$foo.animate({ width:'show' }, 1000);
setTimeout(function(){
equals( $foo.queue().length, 3, "All 3 still in the queue" );
var nw = $foo.width();
ok( nw != w, "An animation occurred " + nw + "px " + w + "px");
$foo.stop();
nw = $foo.width();
ok( nw != w, "Stop didn't reset the animation " + nw + "px " + w + "px");
equals( $foo.queue().length, 2, "The next animation continued" );
$foo.stop(true);
start();
}, 100);
});
test("stop(clearQueue)", function() {
expect(4);
stop();
var $foo = $("#nothiddendiv");
var w = 0;
$foo.hide().width(200).width();
$foo.animate({ width:'show' }, 1000);
$foo.animate({ width:'hide' }, 1000);
$foo.animate({ width:'show' }, 1000);
setTimeout(function(){
var nw = $foo.width();
ok( nw != w, "An animation occurred " + nw + "px " + w + "px");
$foo.stop(true);
nw = $foo.width();
ok( nw != w, "Stop didn't reset the animation " + nw + "px " + w + "px");
equals( $foo.queue().length, 0, "The animation queue was cleared" );
setTimeout(function(){
equals( nw, $foo.width(), "The animation didn't continue" );
start();
}, 100);
}, 100);
});
test("stop(clearQueue, gotoEnd)", function() {
expect(3);
stop();
var $foo = $("#nothiddendiv");
var w = 0;
$foo.hide().width(200).width();
$foo.animate({ width:'show' }, 1000);
$foo.animate({ width:'hide' }, 1000);
$foo.animate({ width:'show' }, 1000);
$foo.animate({ width:'hide' }, 1000);
setTimeout(function(){
var nw = $foo.width();
ok( nw != w, "An animation occurred " + nw + "px " + w + "px");
$foo.stop(false, true);
nw = $foo.width();
equals( nw, 200, "Stop() reset the animation" );
setTimeout(function(){
equals( $foo.queue().length, 3, "The next animation continued" );
$foo.stop(true);
start();
}, 100);
}, 100);
});
test("toggle()", function() {
expect(3);
var x = $("#foo");
ok( x.is(":visible"), "is visible" );
x.toggle();
ok( x.is(":hidden"), "is hidden" );
x.toggle();
ok( x.is(":visible"), "is visible again" );
});
var visible = {
Normal: function(elem){},
"CSS Hidden": function(elem){
$(this).addClass("hidden");
},
"JS Hidden": function(elem){
$(this).hide();
}
};
var from = {
"CSS Auto": function(elem,prop){
$(elem).addClass("auto" + prop)
.text("This is a long string of text.");
return "";
},
"JS Auto": function(elem,prop){
$(elem).css(prop,"auto")
.text("This is a long string of text.");
return "";
},
"CSS 100": function(elem,prop){
$(elem).addClass("large" + prop);
return "";
},
"JS 100": function(elem,prop){
$(elem).css(prop,prop == "opacity" ? 1 : "100px");
return prop == "opacity" ? 1 : 100;
},
"CSS 50": function(elem,prop){
$(elem).addClass("med" + prop);
return "";
},
"JS 50": function(elem,prop){
$(elem).css(prop,prop == "opacity" ? 0.50 : "50px");
return prop == "opacity" ? 0.5 : 50;
},
"CSS 0": function(elem,prop){
$(elem).addClass("no" + prop);
return "";
},
"JS 0": function(elem,prop){
$(elem).css(prop,prop == "opacity" ? 0 : "0px");
return 0;
}
};
var to = {
"show": function(elem,prop){
$(elem).hide().addClass("wide"+prop);
return "show";
},
"hide": function(elem,prop){
$(elem).addClass("wide"+prop);
return "hide";
},
"100": function(elem,prop){
$(elem).addClass("wide"+prop);
return prop == "opacity" ? 1 : 100;
},
"50": function(elem,prop){
return prop == "opacity" ? 0.50 : 50;
},
"0": function(elem,prop){
$(elem).addClass("noback");
return 0;
}
};
function checkOverflowDisplay(){
var o = jQuery.css( this, "overflow" );
equals(o, "visible", "Overflow should be visible: " + o);
equals(jQuery.css( this, "display" ), "inline", "Display shouldn't be tampered with.");
start();
}
test("JS Overflow and Display", function() {
expect(2);
stop();
makeTest( "JS Overflow and Display" )
.addClass("widewidth")
.css({ overflow: "visible", display: "inline" })
.addClass("widewidth")
.text("Some sample text.")
.before("text before")
.after("text after")
.animate({ opacity: 0.5 }, "slow", checkOverflowDisplay);
});
test("CSS Overflow and Display", function() {
expect(2);
stop();
makeTest( "CSS Overflow and Display" )
.addClass("overflow inline")
.addClass("widewidth")
.text("Some sample text.")
.before("text before")
.after("text after")
.animate({ opacity: 0.5 }, "slow", checkOverflowDisplay);
});
jQuery.each( from, function(fn, f){
jQuery.each( to, function(tn, t){
test(fn + " to " + tn, function() {
var elem = makeTest( fn + " to " + tn );
var t_w = t( elem, "width" );
var f_w = f( elem, "width" );
var t_h = t( elem, "height" );
var f_h = f( elem, "height" );
var t_o = t( elem, "opacity" );
var f_o = f( elem, "opacity" );
var num = 0;
if ( t_h == "show" ) num++;
if ( t_w == "show" ) num++;
if ( t_w == "hide"||t_w == "show" ) num++;
if ( t_h == "hide"||t_h == "show" ) num++;
if ( t_o == "hide"||t_o == "show" ) num++;
if ( t_w == "hide" ) num++;
if ( t_o.constructor == Number ) num += 2;
if ( t_w.constructor == Number ) num += 2;
if ( t_h.constructor == Number ) num +=2;
expect(num);
stop();
var anim = { width: t_w, height: t_h, opacity: t_o };
elem.animate(anim, 50, function(){
if ( t_w == "show" )
equals( this.style.display, "block", "Showing, display should block: " + this.style.display);
if ( t_w == "hide"||t_w == "show" )
equals(this.style.width.indexOf(f_w), 0, "Width must be reset to " + f_w + ": " + this.style.width);
if ( t_h == "hide"||t_h == "show" )
equals(this.style.height.indexOf(f_h), 0, "Height must be reset to " + f_h + ": " + this.style.height);
var cur_o = jQuery.attr(this.style, "opacity");
if ( cur_o !== "" ) cur_o = parseFloat( cur_o );
if ( t_o == "hide"||t_o == "show" )
equals(cur_o, f_o, "Opacity must be reset to " + f_o + ": " + cur_o);
if ( t_w == "hide" )
equals(this.style.display, "none", "Hiding, display should be none: " + this.style.display);
if ( t_o.constructor == Number ) {
equals(cur_o, t_o, "Final opacity should be " + t_o + ": " + cur_o);
ok(jQuery.curCSS(this, "opacity") != "" || cur_o == t_o, "Opacity should be explicitly set to " + t_o + ", is instead: " + cur_o);
}
if ( t_w.constructor == Number ) {
equals(this.style.width, t_w + "px", "Final width should be " + t_w + ": " + this.style.width);
var cur_w = jQuery.css(this,"width");
ok(this.style.width != "" || cur_w == t_w, "Width should be explicitly set to " + t_w + ", is instead: " + cur_w);
}
if ( t_h.constructor == Number ) {
equals(this.style.height, t_h + "px", "Final height should be " + t_h + ": " + this.style.height);
var cur_h = jQuery.css(this,"height");
ok(this.style.height != "" || cur_h == t_h, "Height should be explicitly set to " + t_h + ", is instead: " + cur_w);
}
if ( t_h == "show" ) {
var old_h = jQuery.curCSS(this, "height");
$(elem).append("<br/>Some more text<br/>and some more...");
ok(old_h != jQuery.css(this, "height" ), "Make sure height is auto.");
}
start();
});
});
});
});
var check = ['opacity','height','width','display','overflow'];
jQuery.fn.saveState = function(){
expect(check.length);
stop();
return this.each(function(){
var self = this;
self.save = {};
jQuery.each(check, function(i,c){
self.save[c] = jQuery.css(self,c);
});
});
};
function checkState(){
var self = this;
jQuery.each(this.save, function(c,v){
var cur = jQuery.css(self,c);
equals( v, cur, "Make sure that " + c + " is reset (Old: " + v + " Cur: " + cur + ")");
});
start();
}
// Chaining Tests
test("Chain fadeOut fadeIn", function() {
$('#fadein div').saveState().fadeOut('fast').fadeIn('fast',checkState);
});
test("Chain fadeIn fadeOut", function() {
$('#fadeout div').saveState().fadeIn('fast').fadeOut('fast',checkState);
});
test("Chain hide show", function() {
$('#show div').saveState().hide('fast').show('fast',checkState);
});
test("Chain show hide", function() {
$('#hide div').saveState().show('fast').hide('fast',checkState);
});
test("Chain toggle in", function() {
$('#togglein div').saveState().toggle('fast').toggle('fast',checkState);
});
test("Chain toggle out", function() {
$('#toggleout div').saveState().toggle('fast').toggle('fast',checkState);
});
test("Chain slideDown slideUp", function() {
$('#slidedown div').saveState().slideDown('fast').slideUp('fast',checkState);
});
test("Chain slideUp slideDown", function() {
$('#slideup div').saveState().slideUp('fast').slideDown('fast',checkState);
});
test("Chain slideToggle in", function() {
$('#slidetogglein div').saveState().slideToggle('fast').slideToggle('fast',checkState);
});
test("Chain slideToggle out", function() {
$('#slidetoggleout div').saveState().slideToggle('fast').slideToggle('fast',checkState);
});
function makeTest( text ){
var elem = $("<div></div>")
.attr("id", "test" + makeTest.id++)
.addClass("box");
$("<h4></h4>")
.text( text )
.appendTo("#fx-tests")
.click(function(){
$(this).next().toggle();
})
.after( elem );
return elem;
}
makeTest.id = 1;

164
dom/tests/mochitest/ajax/jquery/test/unit/offset.js поставляемый Normal file
Просмотреть файл

@ -0,0 +1,164 @@
module("offset");
// opens a new window to run the tests against
var testwin = function(name, fn) {
testwin[name] = load_offset_fixture(name);
var interval = setInterval(function() {
if (testwin[name] && testwin[name].$ && testwin[name].$.isReady) {
clearInterval(interval);
test(name, fn);
}
}, 0);
function load_offset_fixture(name) {
var win = window.open( "./data/offset/" + name + ".html?num"+parseInt(Math.random()*1000), name, 'left=0,top=0,width=500,height=500,toolbar=1,resizable=0' );
if ( !win ) {
alert("Please disable your popup blocker for the offset test suite");
throw "Please disable your popup blocker for the offset test suite";
}
return win;
}
};
testwin("absolute", function() {
var $w = testwin["absolute"].$;
equals( $w('#absolute-1').offset().top, 1, "$('#absolute-1').offset().top" );
equals( $w('#absolute-1').offset().left, 1, "$('#absolute-1').offset().left" );
equals( $w('#absolute-1-1').offset().top, 5, "$('#absolute-1-1').offset().top" );
equals( $w('#absolute-1-1').offset().left, 5, "$('#absolute-1-1').offset().left" );
equals( $w('#absolute-1-1-1').offset().top, 9, "$('#absolute-1-1-1').offset().top" );
equals( $w('#absolute-1-1-1').offset().left, 9, "$('#absolute-1-1-1').offset().left" );
equals( $w('#absolute-2').offset().top, 20, "$('#absolute-2').offset().top" );
equals( $w('#absolute-2').offset().left, 20, "$('#absolute-2').offset().left" );
equals( $w('#absolute-1').position().top, 0, "$('#absolute-1').position().top" );
equals( $w('#absolute-1').position().left, 0, "$('#absolute-1').position().left" );
equals( $w('#absolute-1-1').position().top, 1, "$('#absolute-1-1').position().top" );
equals( $w('#absolute-1-1').position().left, 1, "$('#absolute-1-1').position().left" );
equals( $w('#absolute-1-1-1').position().top, 1, "$('#absolute-1-1-1').position().top" );
equals( $w('#absolute-1-1-1').position().left, 1, "$('#absolute-1-1-1').position().left" );
equals( $w('#absolute-2').position().top, 19, "$('#absolute-2').position().top" );
equals( $w('#absolute-2').position().left, 19, "$('#absolute-2').position().left" );
testwin["absolute"].close();
});
testwin("relative", function() {
var $w = testwin["relative"].$;
// IE is collapsing the top margin of 1px
equals( $w('#relative-1').offset().top, $.browser.msie ? 6 : 7, "$('#relative-1').offset().top" );
equals( $w('#relative-1').offset().left, 7, "$('#relative-1').offset().left" );
// IE is collapsing the top margin of 1px
equals( $w('#relative-1-1').offset().top, $.browser.msie ? 13 : 15, "$('#relative-1-1').offset().top" );
equals( $w('#relative-1-1').offset().left, 15, "$('#relative-1-1').offset().left" );
// IE is collapsing the top margin of 1px
equals( $w('#relative-2').offset().top, $.browser.msie ? 141 : 142, "$('#relative-2').offset().top" );
equals( $w('#relative-2').offset().left, 27, "$('#relative-2').offset().left" );
// IE is collapsing the top margin of 1px
equals( $w('#relative-1').position().top, $.browser.msie ? 5 : 6, "$('#relative-1').position().top" );
equals( $w('#relative-1').position().left, 6, "$('#relative-1').position().left" );
// IE is collapsing the top margin of 1px
equals( $w('#relative-1-1').position().top, $.browser.msie ? 4 : 5, "$('#relative-1-1').position().top" );
equals( $w('#relative-1-1').position().left, 5, "$('#relative-1-1').position().left" );
// IE is collapsing the top margin of 1px
equals( $w('#relative-2').position().top, $.browser.msie ? 140 : 141, "$('#relative-2').position().top" );
equals( $w('#relative-2').position().left, 26, "$('#relative-2').position().left" );
testwin["relative"].close();
});
testwin("static", function() {
var $w = testwin["static"].$;
// IE is collapsing the top margin of 1px
equals( $w('#static-1').offset().top, $.browser.msie ? 6 : 7, "$('#static-1').offset().top" );
equals( $w('#static-1').offset().left, 7, "$('#static-1').offset().left" );
// IE is collapsing the top margin of 1px
equals( $w('#static-1-1').offset().top, $.browser.msie ? 13 : 15, "$('#static-1-1').offset().top" );
equals( $w('#static-1-1').offset().left, 15, "$('#static-1-1').offset().left" );
// IE is collapsing the top margin of 1px
equals( $w('#static-1-1-1').offset().top, $.browser.msie ? 20 : 23, "$('#static-1-1-1').offset().top" );
equals( $w('#static-1-1-1').offset().left, 23, "$('#static-1-1-1').offset().left" );
// IE is collapsing the top margin of 1px
equals( $w('#static-2').offset().top, $.browser.msie ? 121 : 122, "$('#static-2').offset().top" );
equals( $w('#static-2').offset().left, 7, "$('#static-2').offset().left" );
// IE is collapsing the top margin of 1px
equals( $w('#static-1').position().top, $.browser.msie ? 5 : 6, "$('#static-1').position().top" );
equals( $w('#static-1').position().left, 6, "$('#static-1').position().left" );
// IE is collapsing the top margin of 1px
equals( $w('#static-1-1').position().top, $.browser.msie ? 12 : 14, "$('#static-1-1').position().top" );
equals( $w('#static-1-1').position().left, 14, "$('#static-1-1').position().left" );
// IE is collapsing the top margin of 1px
equals( $w('#static-1-1-1').position().top, $.browser.msie ? 19 : 22, "$('#static-1-1-1').position().top" );
equals( $w('#static-1-1-1').position().left, 22, "$('#static-1-1-1').position().left" );
// IE is collapsing the top margin of 1px
equals( $w('#static-2').position().top, $.browser.msie ? 120 : 121, "$('#static-2').position().top" );
equals( $w('#static-2').position().left, 6, "$('#static-2').position().left" );
testwin["static"].close();
});
if ( !$.browser.msie || ($.browser.msie && parseInt($.browser.version) > 6) )
testwin("fixed", function() {
var $w = testwin["fixed"].$;
equals( $w('#fixed-1').offset().top, 1001, "$('#fixed-1').offset().top" );
equals( $w('#fixed-1').offset().left, $.browser.msie ? 994 : 1001, "$('#fixed-1').offset().left" );
equals( $w('#fixed-2').offset().top, 1021, "$('#fixed-2').offset().top" );
equals( $w('#fixed-2').offset().left, $.browser.msie ? 1014 : 1021, "$('#fixed-2').offset().left" );
testwin["fixed"].close();
});
testwin("table", function() {
var $w = testwin["table"].$;
equals( $w('#table-1').offset().top, 6, "$('#table-1').offset().top" );
equals( $w('#table-1').offset().left, 6, "$('#table-1').offset().left" );
equals( $w('#th-1').offset().top, 10, "$('#table-1').offset().top" );
equals( $w('#th-1').offset().left, 10, "$('#table-1').offset().left" );
equals( $w('#th-2').offset().top, 10, "$('#table-1').offset().top" );
equals( $w('#th-2').offset().left, 116, "$('#table-1').offset().left" );
testwin["table"].close();
});
testwin("scroll", function() {
var $w = testwin["scroll"].$;
// IE is collapsing the top margin of 1px
equals( $w('#scroll-1').offset().top, $.browser.msie ? 6 : 7, "$('#scroll-1').offset().top" );
equals( $w('#scroll-1').offset().left, 7, "$('#scroll-1').offset().left" );
// IE is collapsing the top margin of 1px
equals( $w('#scroll-1-1').offset().top, $.browser.msie ? 9 : 11, "$('#scroll-1-1').offset().top" );
equals( $w('#scroll-1-1').offset().left, 11, "$('#scroll-1-1').offset().left" );
testwin["scroll"].close();
});

224
dom/tests/mochitest/ajax/jquery/test/unit/selector.js поставляемый Normal file
Просмотреть файл

@ -0,0 +1,224 @@
module("selector");
test("element", function() {
expect(9);
ok( $("*").size() >= 30, "Select all" );
var all = $("*"), good = true;
for ( var i = 0; i < all.length; i++ )
if ( all[i].nodeType == 8 )
good = false;
ok( good, "Select all elements, no comment nodes" );
t( "Element Selector", "p", ["firstp","ap","sndp","en","sap","first"] );
t( "Element Selector", "body", ["body"] );
t( "Element Selector", "html", ["html"] );
t( "Parent Element", "div p", ["firstp","ap","sndp","en","sap","first"] );
equals( $("param", "#object1").length, 2, "Object/param as context" );
ok( $("#length").length, '&lt;input name="length"&gt; cannot be found under IE, see #945' );
ok( $("#lengthtest input").length, '&lt;input name="length"&gt; cannot be found under IE, see #945' );
});
if ( location.protocol != "file:" ) {
test("Element Selector with underscore", function() {
expect(1);
stop();
$.get("data/with_fries.xml", function(xml) {
equals( $("foo_bar", xml).length, 1, "Element Selector with underscore" );
start();
});
});
}
test("broken", function() {
expect(7);
t( "Broken Selector", "[", [] );
t( "Broken Selector", "(", [] );
t( "Broken Selector", "{", [] );
t( "Broken Selector", "<", [] );
t( "Broken Selector", "()", [] );
t( "Broken Selector", "<>", [] );
t( "Broken Selector", "{}", [] );
});
test("id", function() {
expect(25);
t( "ID Selector", "#body", ["body"] );
t( "ID Selector w/ Element", "body#body", ["body"] );
t( "ID Selector w/ Element", "ul#first", [] );
t( "ID selector with existing ID descendant", "#firstp #simon1", ["simon1"] );
t( "ID selector with non-existant descendant", "#firstp #foobar", [] );
t( "ID selector using UTF8", "#台北Táiběi", ["台北Táiběi"] );
t( "Multiple ID selectors using UTF8", "#台北Táiběi, #台北", ["台北Táiběi","台北"] );
t( "Descendant ID selector using UTF8", "div #台北", ["台北"] );
t( "Child ID selector using UTF8", "form > #台北", ["台北"] );
t( "Escaped ID", "#foo\\:bar", ["foo:bar"] );
t( "Escaped ID", "#test\\.foo\\[5\\]bar", ["test.foo[5]bar"] );
t( "Descendant escaped ID", "div #foo\\:bar", ["foo:bar"] );
t( "Descendant escaped ID", "div #test\\.foo\\[5\\]bar", ["test.foo[5]bar"] );
t( "Child escaped ID", "form > #foo\\:bar", ["foo:bar"] );
t( "Child escaped ID", "form > #test\\.foo\\[5\\]bar", ["test.foo[5]bar"] );
t( "ID Selector, child ID present", "#form > #radio1", ["radio1"] ); // bug #267
t( "ID Selector, not an ancestor ID", "#form #first", [] );
t( "ID Selector, not a child ID", "#form > #option1a", [] );
t( "All Children of ID", "#foo > *", ["sndp", "en", "sap"] );
t( "All Children of ID with no children", "#firstUL/*", [] );
$('<a name="tName1">tName1 A</a><a name="tName2">tName2 A</a><div id="tName1">tName1 Div</div>').appendTo('#main');
equals( $("#tName1")[0].id, 'tName1', "ID selector with same value for a name attribute" );
equals( $("#tName2").length, 0, "ID selector non-existing but name attribute on an A tag" );
t( "ID Selector on Form with an input that has a name of 'id'", "#lengthtest", ["lengthtest"] );
t( "ID selector with non-existant ancestor", "#asdfasdf #foobar", [] ); // bug #986
isSet( $("body").find("div#form"), [], "ID selector within the context of another element" );
});
test("class", function() {
expect(16);
t( "Class Selector", ".blog", ["mark","simon"] );
t( "Class Selector", ".blog.link", ["simon"] );
t( "Class Selector w/ Element", "a.blog", ["mark","simon"] );
t( "Parent Class Selector", "p .blog", ["mark","simon"] );
t( "Class selector using UTF8", ".台北Táiběi", ["utf8class1"] );
t( "Class selector using UTF8", ".台北", ["utf8class1","utf8class2"] );
t( "Class selector using UTF8", ".台北Táiběi.台北", ["utf8class1"] );
t( "Class selector using UTF8", ".台北Táiběi, .台北", ["utf8class1","utf8class2"] );
t( "Descendant class selector using UTF8", "div .台北Táiběi", ["utf8class1"] );
t( "Child class selector using UTF8", "form > .台北Táiběi", ["utf8class1"] );
t( "Escaped Class", ".foo\\:bar", ["foo:bar"] );
t( "Escaped Class", ".test\\.foo\\[5\\]bar", ["test.foo[5]bar"] );
t( "Descendant scaped Class", "div .foo\\:bar", ["foo:bar"] );
t( "Descendant scaped Class", "div .test\\.foo\\[5\\]bar", ["test.foo[5]bar"] );
t( "Child escaped Class", "form > .foo\\:bar", ["foo:bar"] );
t( "Child escaped Class", "form > .test\\.foo\\[5\\]bar", ["test.foo[5]bar"] );
});
test("multiple", function() {
expect(4);
t( "Comma Support", "a.blog, p", ["mark","simon","firstp","ap","sndp","en","sap","first"] );
t( "Comma Support", "a.blog , p", ["mark","simon","firstp","ap","sndp","en","sap","first"] );
t( "Comma Support", "a.blog ,p", ["mark","simon","firstp","ap","sndp","en","sap","first"] );
t( "Comma Support", "a.blog,p", ["mark","simon","firstp","ap","sndp","en","sap","first"] );
});
test("child and adjacent", function() {
expect(37);
t( "Child", "p > a", ["simon1","google","groups","mark","yahoo","simon"] );
t( "Child", "p> a", ["simon1","google","groups","mark","yahoo","simon"] );
t( "Child", "p >a", ["simon1","google","groups","mark","yahoo","simon"] );
t( "Child", "p>a", ["simon1","google","groups","mark","yahoo","simon"] );
t( "Child w/ Class", "p > a.blog", ["mark","simon"] );
t( "All Children", "code > *", ["anchor1","anchor2"] );
t( "All Grandchildren", "p > * > *", ["anchor1","anchor2"] );
t( "Adjacent", "a + a", ["groups"] );
t( "Adjacent", "a +a", ["groups"] );
t( "Adjacent", "a+ a", ["groups"] );
t( "Adjacent", "a+a", ["groups"] );
t( "Adjacent", "p + p", ["ap","en","sap"] );
t( "Comma, Child, and Adjacent", "a + a, code > a", ["groups","anchor1","anchor2"] );
t( "First Child", "p:first-child", ["firstp","sndp"] );
t( "Nth Child", "p:nth-child(1)", ["firstp","sndp"] );
t( "Last Child", "p:last-child", ["sap"] );
t( "Last Child", "a:last-child", ["simon1","anchor1","mark","yahoo","anchor2","simon"] );
t( "Nth-child", "#main form#form > *:nth-child(2)", ["text2"] );
t( "Nth-child", "#main form#form > :nth-child(2)", ["text2"] );
t( "Nth-child", "#form select:first option:nth-child(3)", ["option1c"] );
t( "Nth-child", "#form select:first option:nth-child(0n+3)", ["option1c"] );
t( "Nth-child", "#form select:first option:nth-child(1n+0)", ["option1a", "option1b", "option1c", "option1d"] );
t( "Nth-child", "#form select:first option:nth-child(1n)", ["option1a", "option1b", "option1c", "option1d"] );
t( "Nth-child", "#form select:first option:nth-child(n)", ["option1a", "option1b", "option1c", "option1d"] );
t( "Nth-child", "#form select:first option:nth-child(even)", ["option1b", "option1d"] );
t( "Nth-child", "#form select:first option:nth-child(odd)", ["option1a", "option1c"] );
t( "Nth-child", "#form select:first option:nth-child(2n)", ["option1b", "option1d"] );
t( "Nth-child", "#form select:first option:nth-child(2n+1)", ["option1a", "option1c"] );
t( "Nth-child", "#form select:first option:nth-child(3n)", ["option1c"] );
t( "Nth-child", "#form select:first option:nth-child(3n+1)", ["option1a", "option1d"] );
t( "Nth-child", "#form select:first option:nth-child(3n+2)", ["option1b"] );
t( "Nth-child", "#form select:first option:nth-child(3n+3)", ["option1c"] );
t( "Nth-child", "#form select:first option:nth-child(3n-1)", ["option1b"] );
t( "Nth-child", "#form select:first option:nth-child(3n-2)", ["option1a", "option1d"] );
t( "Nth-child", "#form select:first option:nth-child(3n-3)", ["option1c"] );
t( "Nth-child", "#form select:first option:nth-child(3n+0)", ["option1c"] );
t( "Nth-child", "#form select:first option:nth-child(-n+3)", ["option1a", "option1b", "option1c"] );
});
test("attributes", function() {
expect(20);
t( "Attribute Exists", "a[title]", ["google"] );
t( "Attribute Exists", "*[title]", ["google"] );
t( "Attribute Exists", "[title]", ["google"] );
t( "Attribute Equals", "a[rel='bookmark']", ["simon1"] );
t( "Attribute Equals", 'a[rel="bookmark"]', ["simon1"] );
t( "Attribute Equals", "a[rel=bookmark]", ["simon1"] );
t( "Multiple Attribute Equals", "#form input[type='hidden'],#form input[type='radio']", ["hidden1","radio1","radio2"] );
t( "Multiple Attribute Equals", "#form input[type=\"hidden\"],#form input[type='radio']", ["hidden1","radio1","radio2"] );
t( "Multiple Attribute Equals", "#form input[type=hidden],#form input[type=radio]", ["hidden1","radio1","radio2"] );
t( "Attribute selector using UTF8", "span[lang=中文]", ["台北"] );
t( "Attribute Begins With", "a[href ^= 'http://www']", ["google","yahoo"] );
t( "Attribute Ends With", "a[href $= 'org/']", ["mark"] );
t( "Attribute Contains", "a[href *= 'google']", ["google","groups"] );
t("Select options via [selected]", "#select1 option[selected]", ["option1a"] );
t("Select options via [selected]", "#select2 option[selected]", ["option2d"] );
t("Select options via [selected]", "#select3 option[selected]", ["option3b", "option3c"] );
t( "Grouped Form Elements", "input[name='foo[bar]']", ["hidden2"] );
t( ":not() Existing attribute", "#form select:not([multiple])", ["select1", "select2"]);
t( ":not() Equals attribute", "#form select:not([name=select1])", ["select2", "select3"]);
t( ":not() Equals quoted attribute", "#form select:not([name='select1'])", ["select2", "select3"]);
});
test("pseudo (:) selectors", function() {
expect(35);
t( "First Child", "p:first-child", ["firstp","sndp"] );
t( "Last Child", "p:last-child", ["sap"] );
t( "Only Child", "a:only-child", ["simon1","anchor1","yahoo","anchor2"] );
t( "Empty", "ul:empty", ["firstUL"] );
t( "Enabled UI Element", "#form input:enabled", ["text1","radio1","radio2","check1","check2","hidden1","hidden2","name"] );
t( "Disabled UI Element", "#form input:disabled", ["text2"] );
t( "Checked UI Element", "#form input:checked", ["radio2","check1"] );
t( "Selected Option Element", "#form option:selected", ["option1a","option2d","option3b","option3c"] );
t( "Text Contains", "a:contains('Google')", ["google","groups"] );
t( "Text Contains", "a:contains('Google Groups')", ["groups"] );
t( "Element Preceded By", "p ~ div", ["foo","fx-queue","fx-tests", "moretests"] );
t( "Not", "a.blog:not(.link)", ["mark"] );
t( "Not - multiple", "#form option:not(:contains('Nothing'),#option1b,:selected)", ["option1c", "option1d", "option2b", "option2c", "option3d"] );
t( "Not - complex", "#form option:not([id^='opt']:gt(0):nth-child(-n+3))", [ "option1a", "option1d", "option2d", "option3d"] );
t( "Not - recursive", "#form option:not(:not(:selected))[id^='option3']", [ "option3b", "option3c"] );
t( "nth Element", "p:nth(1)", ["ap"] );
t( "First Element", "p:first", ["firstp"] );
t( "Last Element", "p:last", ["first"] );
t( "Even Elements", "p:even", ["firstp","sndp","sap"] );
t( "Odd Elements", "p:odd", ["ap","en","first"] );
t( "Position Equals", "p:eq(1)", ["ap"] );
t( "Position Greater Than", "p:gt(0)", ["ap","sndp","en","sap","first"] );
t( "Position Less Than", "p:lt(3)", ["firstp","ap","sndp"] );
t( "Is A Parent", "p:parent", ["firstp","ap","sndp","en","sap","first"] );
t( "Is Visible", "#form input:visible", ["text1","text2","radio1","radio2","check1","check2","name"] );
t( "Is Hidden", "#form input:hidden", ["hidden1","hidden2"] );
t( "Form element :input", "#form :input", ["text1", "text2", "radio1", "radio2", "check1", "check2", "hidden1", "hidden2", "name", "button", "area1", "select1", "select2", "select3"] );
t( "Form element :radio", "#form :radio", ["radio1", "radio2"] );
t( "Form element :checkbox", "#form :checkbox", ["check1", "check2"] );
t( "Form element :text", "#form :text", ["text1", "text2", "hidden2", "name"] );
t( "Form element :radio:checked", "#form :radio:checked", ["radio2"] );
t( "Form element :checkbox:checked", "#form :checkbox:checked", ["check1"] );
t( "Form element :checkbox:checked, :radio:checked", "#form :checkbox:checked, #form :radio:checked", ["check1", "radio2"] );
t( "Headers", ":header", ["header", "banner", "userAgent"] );
t( "Has Children - :has()", "p:has(a)", ["firstp","ap","en","sap"] );
});

Просмотреть файл

@ -0,0 +1 @@
1.2.6