Monday, May 4, 2009

jQuery(八)----Plugins

Keep Moving...

8. Plugins

8.1 Accordion

8.1.1 Accordion(settings)

Make the selected elements Accordion widgets. ? Semantic requirements:

If the structure of your container is flat with unique tags for header and content elements, eg. a definition list 

(dl > dt + dd), you don't have to specify any options at all.

If your structure uses the same elements for header and content or uses some kind of nested structure, you have to 

specify the header elements, eg. via class, see the second example.

Use activate(Number) to change the active content programmatically.

返回值

jQuery

参数

settings (Object): key/value pairs of optional settings.
Hash 选项

active (String|Element|jQuery|Boolean): Selector for the active element, default is the first child, set to false 

to display none at start
header (String|Element|jQuery): Selector for the header element, eg. div.title, a.head, default is the first 

child's tagname
showSpeed (String|Number): Speed for the slideIn, default is 'slow'
hideSpeed (String|Number): Speed for the slideOut, default is 'fast'
selectedClass (String): Class for active header elements, default is 'selected'
示例

说明:

Creates a Accordion from the given definition list

HTML 代码:

<dl id="list1"><dt>Header 1><dd>Content 1</dd>[...]</dl>
jQuery 代码:

$('#list1').Accordion();
说明:

Creates a Accordion from the given div structure

HTML 代码:

<div id="nav"><div><div class="title">Header 1><div>Content 1</div></div>

[...]</div>
jQuery 代码:

$('#list2').Accordion({ header: 'div.title' });
说明:

Creates a Accordion from the given navigation list

HTML 代码:

<ul id="nav"> <li> <a class="head">Header 1> <ul> <li><a href="#">Link 

1</a></li> <li><a href="#">Link 2></a></li> </ul> </li> [...] 

</ul>
jQuery 代码:

$('#nav').Accordion({ header: 'a.head' });
说明:

Updates the #status element with the text of the selected header every time the accordion changes

jQuery 代码:

$('#accordion').Accordion().change(function(event, newHeader, oldHeader, newContent, oldContent) { 

$('#status').html(newHeader.text()); });

8.1.2 activate(index)

Activate a content part of the Accordion programmatically with the position zero-based index.

If the index is not specified, it defaults to zero, if it is an invalid index, eg. a string, nothing happens.

Requires jQuery core revision >= 557.

返回值

jQuery

参数

index (Number): An Integer specifying the zero-based index of the content to be activated. Defaults to 0.
示例

说明:

Activate the second content of the Accordion contained in <div id="accordion">.

jQuery 代码:

$('#accordion').activate(1);
说明:

Activate the first content of the Accordion contained in <ul id="nav">.

jQuery 代码:

$('#nav').activate();

8.2 Button
button(hash)

Creates a button from an image element.

This function attempts to mimic the functionality of the "button" found in modern day GUIs. There are two different 

buttons you can create using this plugin; Normal buttons, and Toggle buttons.

返回值

jQuery

参数

hash (hOptions): with options, described below. sPath Full path to the images, either relative or with full URL 

sExt Extension of the used images (jpg|gif|png) sName Name of the button, if not specified, try to fetch from id 

iWidth Width of the button, if not specified, try to fetch from element.width iHeight Height of the button, if not 

specified, try to fetch from element.height onAction Function to call when clicked / toggled. In case of a string, 

the element is wrapped inside an href tag. bToggle Do we need to create a togglebutton? (boolean) bState Initial 

state of the button? (boolean) sType Type of hover to create (img|css)

8.3 Center
center()

Takes all matched elements and centers them, absolutely, within the context of their parent element. Great for 

doing slideshows.

返回值

jQuery

示例

jQuery 代码:

$("div img").center();

8.4 Cookie
8.4.1 $.cookie(name)

Get the value of a cookie with the given name.

返回值

String

参数

name (String): The name of the cookie.
示例

说明:

Get the value of a cookie.

jQuery 代码:

$.cookie('the_cookie');

8.4.2 $.cookie(name, value, options)

Create a cookie with the given name and value and other optional parameters.

返回值

undefined

参数

name (String): The name of the cookie.
value (String): The value of the cookie.
options (Object): An object literal containing key/value pairs to provide optional cookie attributes.
Hash 选项

expires (Number|Date): Either an integer specifying the expiration date from now on in days or a Date object. If a 

negative value is specified (e.g. a date in the past), the cookie will be deleted. If set to null or omitted, the 

cookie will be a session cookie and will not be retained when the the browser exits.
path (String): The value of the path atribute of the cookie (default: path of page that created the cookie).
domain (String): The value of the domain attribute of the cookie (default: domain of page that created the cookie).
secure (Boolean): If true, the secure attribute of the cookie will be set and the cookie transmission will require 

a secure protocol (like HTTPS).
示例

说明:

Set the value of a cookie.

jQuery 代码:

$.cookie('the_cookie', 'the_value');
说明:

Create a cookie with all available options.

jQuery 代码:

$.cookie('the_cookie', 'the_value', {expires: 7, path: '/', domain: 'jquery.com', secure: true});
说明:

Create a session cookie.

jQuery 代码:

$.cookie('the_cookie', 'the_value');
说明:

Delete a cookie by setting a date in the past.

jQuery 代码:

$.cookie('the_cookie', '', {expires: -1});

8.5 Dimensions

8.5.1 height()

Returns the css height value for the first matched element. If used on document, returns the document's height 

(innerHeight) If used on window, returns the viewport's (window) height

返回值

Object

示例

jQuery 代码:

$("#testdiv").height()
结果:

"200px"
jQuery 代码:

$(document).height();
结果:

800
jQuery 代码:

$(window).height();
结果:

400

8.5.2 innerHeight()

Returns the inner height value (without border) for the first matched element. If used on document, returns the 

document's height (innerHeight) If used on window, returns the viewport's (window) height

返回值

Number

示例

jQuery 代码:

$("#testdiv").innerHeight()
结果:

800

8.5.3 innerWidth()

Returns the inner width value (without border) for the first matched element. If used on document, returns the 

document's Width (innerWidth) If used on window, returns the viewport's (window) width

返回值

Number

示例

jQuery 代码:

$("#testdiv").innerWidth()
结果:

1000

8.5.4 offset()

This returns an object with top, left, width, height, borderLeft, borderTop, marginLeft, marginTop, scrollLeft, 

scrollTop, pageXOffset, pageYOffset.

The top and left values include the scroll offsets but the scrollLeft and scrollTop properties of the returned 

object are the combined scroll offets of the parent elements (not including the window scroll offsets). This is not 

the same as the element's scrollTop and scrollLeft.

For accurate readings make sure to use pixel values.

返回值

Object

8.5.5 offset(refElement)

This returns an object with top, left, width, height, borderLeft, borderTop, marginLeft, marginTop, scrollLeft, 

scrollTop, pageXOffset, pageYOffset.

The top and left values include the scroll offsets but the scrollLeft and scrollTop properties of the returned 

object are the combined scroll offets of the parent elements (not including the window scroll offsets). This is not 

the same as the element's scrollTop and scrollLeft.

For accurate readings make sure to use pixel values.

返回值

Object

参数

refElement (String): This is an expression. The offset returned will be relative to the first matched element.


8.5.6 offset(refElement)

This returns an object with top, left, width, height, borderLeft, borderTop, marginLeft, marginTop, scrollLeft, 

scrollTop, pageXOffset, pageYOffset.

The top and left values include the scroll offsets but the scrollLeft and scrollTop properties of the returned 

object are the combined scroll offets of the parent elements (not including the window scroll offsets). This is not 

the same as the element's scrollTop and scrollLeft.

For accurate readings make sure to use pixel values.

返回值

Object

参数

refElement (jQuery): The offset returned will be relative to the first matched element.

8.5.7 offset(refElement)

This returns an object with top, left, width, height, borderLeft, borderTop, marginLeft, marginTop, scrollLeft, 

scrollTop, pageXOffset, pageYOffset.

The top and left values include the scroll offsets but the scrollLeft and scrollTop properties of the returned 

object are the combined scroll offets of the parent elements (not including the window scroll offsets). This is not 

the same as the element's scrollTop and scrollLeft.

For accurate readings make sure to use pixel values.

返回值

Object

参数

refElement (HTMLElement): The offset returned will be relative to this element.

8.5.8 outerHeight()

Returns the outer height value (including border) for the first matched element. Cannot be used on document or 

window.

返回值

Number

示例

jQuery 代码:

$("#testdiv").outerHeight()
结果:

1000

8.5.9 outerWidth()

Returns the outer width value (including border) for the first matched element. Cannot be used on document or 

window.

返回值

Number

示例

jQuery 代码:

$("#testdiv").outerWidth()
结果:

1000

8.5.10 scrollLeft()

Returns how many pixels the user has scrolled to the right (scrollLeft). Works on containers with overflow: auto 

and window/document.

返回值

Number

示例

jQuery 代码:

$("#testdiv").scrollLeft()
结果:

100

8.5.11 scrollTop()

Returns how many pixels the user has scrolled to the bottom (scrollTop). Works on containers with overflow: auto 

and window/document.

返回值

Number

示例

jQuery 代码:

$("#testdiv").scrollTop()
结果:

100

8.5.12 width()

Returns the css width value for the first matched element. If used on document, returns the document's width 

(innerWidth) If used on window, returns the viewport's (window) width

返回值

Object

示例

jQuery 代码:

$("#testdiv").width()
结果:

"200px"
jQuery 代码:

$(document).width();
结果:

800
jQuery 代码:

$(window).width();
结果:

400

8.6 Form

8.6.1 ajaxForm(object)

ajaxForm() provides a mechanism for fully automating form submission.

The advantages of using this method instead of ajaxSubmit() are:

1: This method will include coordinates for <input type="image" /> elements (if the element is used to submit 

the form). 2. This method will include the submit element's name/value data (for the element that was used to 

submit the form). 3. This method binds the submit() method to the form for you.

Note that for accurate x/y coordinates of image submit elements in all browsers you need to also use the 

"dimensions" plugin (this method will auto-detect its presence).

The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely passes the options 

argument along after properly binding events for submit elements and the form itself. See ajaxSubmit for a full 

description of the options argument.

返回值

jQuery

参数

object (options): literal containing options which control the form submission process
示例

说明:

Bind form's submit event so that 'myTargetDiv' is updated with the server response when the form is submitted.

jQuery 代码:

var options = { target: '#myTargetDiv' }; $('#myForm').ajaxSForm(options);
说明:

Bind form's submit event so that server response is alerted after the form is submitted.

jQuery 代码:

var options = { success: function(responseText) { alert(responseText); } }; $('#myForm').ajaxSubmit(options);
说明:

Bind form's submit event so that pre-submit callback is invoked before the form is submitted.

jQuery 代码:

var options = { beforeSubmit: function(formArray, jqForm) { if (formArray.length == 0) { alert('Please enter 

data.'); return false; } } }; $('#myForm').ajaxSubmit(options);

8.6.2 ajaxSubmit(object)

ajaxSubmit() provides a mechanism for submitting an HTML form using AJAX.

ajaxSubmit accepts a single argument which can be either a success callback function or an options Object. If a 

function is provided it will be invoked upon successful completion of the submit and will be passed the response 

from the server. If an options Object is provided, the following attributes are supported:

target: Identifies the element(s) in the page to be updated with the server response. This value may be specified 

as a jQuery selection string, a jQuery object, or a DOM element. default value: null

url: URL to which the form data will be submitted. default value: value of form's 'action' attribute

method:

返回值

jQuery

参数

object (options): literal containing options which control the form submission process
示例

说明:

Submit form and alert server response

jQuery 代码:

$('#myForm').ajaxSubmit(function(data) { alert('Form submit succeeded! Server returned: ' + data); });
说明:

Submit form and update page element with server response

jQuery 代码:

var options = { target: '#myTargetDiv' }; $('#myForm').ajaxSubmit(options);
说明:

Submit form and alert the server response

jQuery 代码:

var options = { success: function(responseText) { alert(responseText); } }; $('#myForm').ajaxSubmit(options);
说明:

Pre-submit validation which aborts the submit operation if form data is empty

jQuery 代码:

var options = { beforeSubmit: function(formArray, jqForm) { if (formArray.length == 0) { alert('Please enter 

data.'); return false; } } }; $('#myForm').ajaxSubmit(options);
说明:

json data returned and evaluated

jQuery 代码:

var options = { url: myJsonUrl.php, dataType: 'json', success: function(data) { // 'data' is an object representing 

the the evaluated json data } }; $('#myForm').ajaxSubmit(options);
说明:

XML data returned from server

jQuery 代码:

var options = { url: myXmlUrl.php, dataType: 'xml', success: function(responseXML) { // responseXML is XML document 

object var data = $('myElement', responseXML).text(); } }; $('#myForm').ajaxSubmit(options);
说明:

submit form and reset it if successful

jQuery 代码:

var options = { resetForm: true }; $('#myForm').ajaxSubmit(options);
说明:

Bind form's submit event to use ajaxSubmit

jQuery 代码:

$('#myForm).submit(function() { $(this).ajaxSubmit(); return false; });

8.6.3 clearForm()

Clears the form data. Takes the following actions on the form's input fields: - input text fields will have their 

'value' property set to the empty string - select elements will have their 'selectedIndex' property set to -1 - 

checkbox and radio inputs will have their 'checked' property set to false - inputs of type submit, button, reset, 

and hidden will not be effected - button elements will not be effected

返回值

jQuery

示例

说明:

Clears all forms on the page.

jQuery 代码:

$('form').clearForm();

8.6.4 clearInputs()

Clears the selected form elements. Takes the following actions on the matched elements: - input text fields will 

have their 'value' property set to the empty string - select elements will have their 'selectedIndex' property set 

to -1 - checkbox and radio inputs will have their 'checked' property set to false - inputs of type submit, button, 

reset, and hidden will not be effected - button elements will not be effected

返回值

jQuery

示例

说明:

Clears all inputs with class myInputs

jQuery 代码:

$('.myInputs').clearInputs();

8.6.5 fieldSerialize(true)

Serializes all field elements in the jQuery object into a query string. This method will return a string in the 

format: name1=value1&name2=value2

The successful argument controls whether or not serialization is limited to 'successful' controls (per 

http://www.w3.org/TR/html4/interact/forms.html#successful-controls). The default value of the successful argument 

is true.

返回值

String

参数

true (successful): if only successful controls should be serialized (default is true)
示例

说明:

Collect the data from all successful input elements into a query string

jQuery 代码:

var data = $("input").formSerialize();
说明:

Collect the data from all successful radio input elements into a query string

jQuery 代码:

var data = $(":radio").formSerialize();
说明:

Collect the data from all successful checkbox input elements in myForm into a query string

jQuery 代码:

var data = $("#myForm :checkbox").formSerialize();
说明:

Collect the data from all checkbox elements in myForm (even the unchecked ones) into a query string

jQuery 代码:

var data = $("#myForm :checkbox").formSerialize(false);
说明:

Collect the data from all successful input, select, textarea and button elements into a query string

jQuery 代码:

var data = $(":input").formSerialize();

8.6.6 fieldValue(successful)

Returns the value of the field element in the jQuery object. If there is more than one field element in the jQuery 

object the value of the first successful one is returned.

The successful argument controls whether or not the field element must be 'successful' (per 

http://www.w3.org/TR/html4/interact/forms.html#successful-controls). The default value of the successful argument 

is true. If this value is false then the value of the first field element in the jQuery object is returned.

Note: If no valid value can be determined the return value will be undifined.

Note: The fieldValue returned for a select-multiple element or for a checkbox input will always be an array if it 

is not undefined.

返回值

String or Array<String>

参数

successful (Boolean): true if value returned must be for a successful controls (default is true)
示例

说明:

Gets the current value of the myPasswordElement element

jQuery 代码:

var data = $("#myPasswordElement").formValue();
说明:

Get the value of the first successful control in the jQuery object.

jQuery 代码:

var data = $("#myForm :input").formValue();
说明:

Get the array of values for the first set of successful checkbox controls in the jQuery object.

jQuery 代码:

var data = $("#myForm :checkbox").formValue();
说明:

Get the value of the select control

jQuery 代码:

var data = $("#mySingleSelect").formValue();
说明:

Get the array of selected values for the select-multiple control

jQuery 代码:

var data = $("#myMultiSelect").formValue();

8.6.7 fieldValue(el, successful)

Returns the value of the field element.

The successful argument controls whether or not the field element must be 'successful' (per 

http://www.w3.org/TR/html4/interact/forms.html#successful-controls). The default value of the successful argument 

is true. If the given element is not successful and the successful arg is not false then the returned value will be 

null.

Note: The fieldValue returned for a select-multiple element will always be an array.

返回值

String or Array<String>

参数

el (Element): The DOM element for which the value will be returned
successful (Boolean): true if value returned must be for a successful controls (default is true)
示例

说明:

Gets the current value of the myPasswordElement element

jQuery 代码:

var data = jQuery.fieldValue($("#myPasswordElement")[0]);

8.6.8 
formSerialize(true)

Serializes form data into a 'submittable' string. This method will return a string in the format: 

name1=value1&name2=value2

The semantic argument can be used to force form serialization in semantic order. If your form must be submitted 

with name/value pairs in semantic order then pass true for this arg, otherwise pass false (or nothing) to avoid the 

overhead for this logic (which can be significant for very large forms).

返回值

String

参数

true (semantic): if serialization must maintain strict semantic ordering of elements (slower)
示例

说明:

Collect all the data from a form into a single string

jQuery 代码:

var data = $("#myForm").formSerialize(); $.ajax('POST', "myscript.cgi", data);

8.6.9 formToArray(true)

formToArray() gathers form element data into an array of objects that can be passed to any of the following ajax 

functions: $.get, $.post, or load. Each object in the array has both a 'name' and 'value' property. An example of 

an array for a simple login form might be:

[ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]

It is this array that is passed to pre-submit callback functions provided to the ajaxSubmit() and ajaxForm() 

methods.

The semantic argument can be used to force form serialization in semantic order. If your form must be submitted 

with name/value pairs in semantic order then pass true for this arg, otherwise pass false (or nothing) to avoid the 

overhead for this logic (which can be significant for very large forms).

返回值

Array<Object>

参数

true (semantic): if serialization must maintain strict semantic ordering of elements (slower)
示例

说明:

Collect all the data from a form and submit it to the server.

jQuery 代码:

var data = $("#myForm").formToArray(); $.post( "myscript.cgi", data );

8.6.10 resetForm()

Resets the form data. Causes all form elements to be reset to their original value.

返回值

jQuery

示例

说明:

Resets all forms on the page.

jQuery 代码:

$('form').resetForm();

8.7 Interface

8.7.1 $.recallDroppables()

Recalculate all Droppables

返回值

jQuery

示例

jQuery 代码:

$.recallDroppable();

8.7.2 $.SortSerialize()

This function returns the hash and an object (can be used as arguments for $.post) for every sortable in the page 

or specific sortables. The hash is based on the 'id' attributes of container and items.

返回值

String

参数

():

8.7.3 Draggable(hash)

Create a draggable element with a number of advanced options including callback, Google Maps type draggables, 

reversion, ghosting, and grid dragging.

返回值

jQuery

参数

hash (Hash): A hash of parameters. All parameters are optional.
Hash 选项

handle (String): The jQuery selector matching the handle that starts the draggable
handle (DOMElement): The DOM Element of the handle that starts the draggable
revert (Boolean): When true, on stop-drag the element returns to initial position
ghosting (Boolean): When true, a copy of the element is moved
zIndex (Integer): zIndex depth for the element while it is being dragged
opacity (Float): A number between 0 and 1 that indicates the opacity of the element while being dragged
grid (Integer): A number of pixels indicating the grid that the element should snap to
grid (Array): A number of x-pixels and y-pixels indicating the grid that the element should snap to
fx (Integer): Duration for the effect (like ghosting or revert) applied to the draggable
containment (String): Define the zone where the draggable can be moved. 'parent' moves it inside parent element, 

while 'document' prevents it from leaving the document and forcing additional scrolling
containment (Array): An 4-element array (topm left, width, height) indicating the containment of the element
axis (String): Set an axis: vertical (with 'vertically') or horizontal (with 'horizontally')
onStart (Function): Callback function triggered when the dragging starts
onStop (Function): Callback function triggered when the dragging stops
onChange (Function): Callback function triggered when the dragging stop and the element was moved at least one 

pixel
onDrag (Function): Callback function triggered while the element is dragged. Receives two parameters: x and y 

coordinates. You can return an object with new coordinates {x: x, y: y} so this way you can interact with the 

dragging process (for instance, build your containment)
insideParent (Boolean): Forces the element to remain inside its parent when being dragged (like Google Maps)
snapDistance (Integer): The element is not moved unless it is dragged more than snapDistance. You can prevent 

accidental dragging and keep regular clicking enabled (for links or form elements, for instance)
cursorAt (Object): The dragged element is moved to the cursor position with the offset specified. Accepts value for 

top, left, right and bottom offset. Basically, this forces the cursor to a particular position during the entire 

drag operation.
autoSize (Boolean): When true, the drag helper is resized to its content, instead of the dragged element's sizes

8.7.4 DraggableDestroy()

Destroy an existing draggable on a collection of elements

返回值

jQuery

示例

jQuery 代码:

$('#drag2').DraggableDestroy();

8.7.5 Droppable(options)

With the Draggables plugin, Droppable allows you to create drop zones for draggable elements.

参数

options (Hash): A hash of options
Hash 选项

accept (String): The class name for draggables to get accepted by the droppable (mandatory)
activeclass (String): When an acceptable draggable is moved, the droppable gets this class
hoverclass (String): When an acceptable draggable is inside the droppable, the droppable gets this class
tolerance (String): Choose from 'pointer', 'intersect', or 'fit'. The pointer options means that the pointer must 

be inside the droppable in order for the draggable to be dropped. The intersect option means that the draggable 

must intersect the droppable. The fit option means that the entire draggable must be inside the droppable.
onDrop (Function): When an acceptable draggable is dropped on a droppable, this callback is called. It passes the 

draggable DOMElement as a parameter.
onHover (Function): When an acceptable draggable is hovered over a droppable, this callback is called. It passes 

the draggable DOMElement as a parameter.
onOut (Function): When an acceptable draggable leaves a droppable, this callback is called. It passes the draggable 

DOMElement as a parameter.
示例

jQuery 代码:

$('#dropzone1').Droppable( { accept : 'dropaccept', activeclass: 'dropzoneactive', hoverclass: 'dropzonehover', 

ondrop: function (drag) { alert(this); //the droppable alert(drag); //the draggable }, fit: true } )

8.7.6 DroppableDestroy()

Destroy an existing droppable on a collection of elements

返回值

jQuery

示例

jQuery 代码:

$('#drag2').DroppableDestroy();

8.7.7 Sortable(options)

Allows you to resort elements within a container by dragging and dropping. Requires the Draggables and Droppables 

plugins. The container and each item inside the container must have an ID. Sortables are especially useful for 

lists.

参数

options (Hash): A hash of options
Hash 选项

accept (String): The class name for items inside the container (mandatory)
activeclass (String): The class for the container when one of its items has started to move
hoverclass (String): The class for the container when an acceptable item is inside it
helperclass (String): The helper is used to point to the place where the item will be moved. This is the class for 

the helper.
opacity (Float): Opacity (between 0 and 1) of the item while being dragged
ghosting (Boolean): When true, the sortable is ghosted when dragged
tolerance (String): Either 'pointer', 'intersect', or 'fit'. See Droppable for more details
fit (Boolean): When true, sortable must be inside the container in order to drop
fx (Integer): Duration for the effect applied to the sortable
onchange (Function): Callback that gets called when the sortable list changed. It takes an array of serialized 

elements
floats (Boolean): True if the sorted elements are floated
containment (String): Use 'parent' to constrain the drag to the container
axis (String): Use 'horizontally' or 'vertically' to constrain dragging to an axis
handle (String): The jQuery selector that indicates the draggable handle
handle (DOMElement): The node that indicates the draggable handle
onHover (Function): Callback that is called when an acceptable item is dragged over the container. Gets the 

hovering DOMElement as a parameter
onOut (Function): Callback that is called when an acceptable item leaves the container. Gets the leaving DOMElement 

as a parameter
cursorAt (Object): The mouse cursor will be moved to the offset on the dragged item indicated by the object, which 

takes "top", "bottom", "left", and "right" keys
onStart (Function): Callback function triggered when the dragging starts
onStop (Function): Callback function triggered when the dragging stops
示例

jQuery 代码:

$('ul').Sortable( { accept : 'sortableitem', activeclass : 'sortableactive', hoverclass : 'sortablehover', 

helperclass : 'sorthelper', opacity: 0.5, fit : false } )

8.7.8 SortableAddItem(elem)

A new item can be added to a sortable by adding it to the DOM and then adding it via SortableAddItem.

返回值

jQuery

参数

elem (DOMElement): A DOM Element to add to the sortable list
示例

jQuery 代码:

$('#sortable1').append('<li id="newitem">new item</li>') .SortableAddItem($("#new_item")[0])

8.8 Metadata

8.8.1 $.meta.setType(type, name)

Sets the type of metadata to use. Metadata is encoded in JSON, and each property in the JSON will become a property 

of the element itself.

There are three supported types of metadata storage:

attr: Inside an attribute. The name parameter indicates which attribute.

class: Inside the class attribute, wrapped in curly braces: { }

elem: Inside a child element (e.g. a script tag). The name parameter indicates which element.

The metadata for an element is loaded the first time the element is accessed via jQuery.

As a result, you can define the metadata type, use $(expr) to load the metadata into the elements matched by expr, 

then redefine the metadata type and run another $(expr) for other elements.

返回值

undefined

参数

type (String): The encoding type
name (String): The name of the attribute to be used to get metadata (optional)
示例

说明:

Reads metadata from the class attribute

HTML 代码:

$.meta.setType("class")
jQuery 代码:

<p id="one" class="some_class {item_id: 1, item_label: 'Label'}">This is a p</p>
说明:

Reads metadata from a "data" attribute

HTML 代码:

$.meta.setType("attr", "data")
jQuery 代码:

<p id="one" class="some_class" data="{item_id: 1, item_label: 'Label'}">This is a p</p>
说明:

Reads metadata from a nested script element

HTML 代码:

$.meta.setType("elem", "script")
jQuery 代码:

<p id="one" class="some_class"><script>{item_id: 1, item_label: 'Label'}</script>This is a 

p</p>

8.8.2 data()

Returns the metadata object for the first member of the jQuery object.

返回值

jQuery

8.9 Tabs

8.9.1 disableTab(position)

Disable a tab, so that clicking it has no effect.

返回值

jQuery

参数

position (Number): An integer specifying the position of the tab (no zero-based index) to be disabled. If this 

parameter is omitted, the first tab will be disabled.
示例

说明:

Disable the second tab of the tab interface contained in <div id="container">.

jQuery 代码:

$('#container').disableTab(2);

8.9.2 enableTab(position)

Enable a tab that has been disabled.

返回值

jQuery

参数

position (Number): An integer specifying the position of the tab (no zero-based index) to be enabled. If this 

parameter is omitted, the first tab will be enabled.
示例

说明:

Enable the second tab of the tab interface contained in <div id="container">.

jQuery 代码:

$('#container').enableTab(2);

8.9.3 tabs(initial, settings)

Create an accessible, unobtrusive tab interface based on a certain HTML structure.

The underlying HTML has to look like this:

<div id="container"> <ul> <li><a href="#section-1">Section 1</a></li> 

<li><a href="#section-2">Section 2</a></li> <li><a href="#section-3">Section 

3</a></li> </ul> <div id="section-1">

</div> <div id="section-2">

</div> <div id="section-3">

</div> </div>

Each anchor in the unordered list points directly to a section below represented by one of the divs (the URI in the 

anchor's href attribute refers to the fragment with the corresponding id). Because such HTML structure is fully 

functional on its own, e.g. without JavaScript, the tab interface is accessible and unobtrusive.

A tab is also bookmarkable via hash in the URL. Use the History/Remote plugin (Tabs will auto-detect its presence) 

to fix the back (and forward) button.

返回值

jQuery

参数

initial (Number): An integer specifying the position of the tab (no zero-based index) that gets first activated, 

e.g. on page load. If a hash in the URL of the page refers to one fragment (tab container) of a tab interface, this 

parameter will be ignored and instead the tab belonging to that fragment in that specific tab interface will be 

activated. Defaults to 1 if omitted.
settings (Object): An object literal containing key/value pairs to provide optional settings.
Hash 选项

disabled (Array<Number>): An array containing the position of the tabs (no zero-based index) that should be 

disabled on initialization. Default value: null.
bookmarkable (Boolean): Boolean flag indicating if support for bookmarking and history (via changing hash in the 

URL of the browser) is enabled. Default value: false, unless the History/Remote plugin is included. In that case 

the default value becomes true. @see $.ajaxHistory.initialize
fxFade (Boolean): Boolean flag indicating whether fade in/out animations are used for tab switching. Can be 

combined with fxSlide. Will overrule fxShow/fxHide. Default value: false.
fxSlide (Boolean): Boolean flag indicating whether slide down/up animations are used for tab switching. Can be 

combined with fxFade. Will overrule fxShow/fxHide. Default value: false.
fxSpeed (String|Number): A string representing one of the three predefined speeds ("slow", "normal", or "fast") or 

the number of milliseconds (e.g. 1000) to run an animation. Default value: "normal".
fxShow (Object): An object literal of the form jQuery's animate function expects for making your own, custom 

animation to reveal a tab upon tab switch. Unlike fxFade or fxSlide this animation is independent from an optional 

hide animation. Default value: null. @see animate
fxHide (Object): An object literal of the form jQuery's animate function expects for making your own, custom 

animation to hide a tab upon tab switch. Unlike fxFade or fxSlide this animation is independent from an optional 

show animation. Default value: null. @see animate
fxShowSpeed (String|Number): A string representing one of the three predefined speeds ("slow", "normal", or "fast") 

or the number of milliseconds (e.g. 1000) to run the animation specified in fxShow. Default value: fxSpeed.
fxHideSpeed (String|Number): A string representing one of the three predefined speeds ("slow", "normal", or "fast") 

or the number of milliseconds (e.g. 1000) to run the animation specified in fxHide. Default value: fxSpeed.
fxAutoHeight (Boolean): Boolean flag that if set to true causes all tab heights to be constant (being the height of 

the tallest tab). Default value: false.
onClick (Function): A function to be invoked upon tab switch, immediatly after a tab has been clicked, e.g. before 

the other's tab content gets hidden. The function gets passed three arguments: the first one is the clicked tab 

(e.g. an anchor element), the second one is the DOM element containing the content of the clicked tab (e.g. the 

div), the third argument is the one of the tab that gets hidden. Default value: null.
onHide (Function): A function to be invoked upon tab switch, immediatly after one tab's content got hidden (with or 

without an animation) and right before the next tab is revealed. The function gets passed three arguments: the 

first one is the clicked tab (e.g. an anchor element), the second one is the DOM element containing the content of 

the clicked tab, (e.g. the div), the third argument is the one of the tab that gets hidden. Default value: null.
onShow (Function): A function to be invoked upon tab switch. This function is invoked after the new tab has been 

revealed, e.g. after the switch is completed. The function gets passed three arguments: the first one is the 

clicked tab (e.g. an anchor element), the second one is the DOM element containing the content of the clicked tab, 

(e.g. the div), the third argument is the one of the tab that gets hidden. Default value: null.
selectedClass (String): The CSS class attached to the li element representing the currently selected (active) tab. 

Default value: "tabs-selected".
disabledClass (String): The CSS class attached to the li element representing a disabled tab. Default value: "tabs

-disabled".
hideClass (String): The CSS class used for hiding inactive tabs. A class is used instead of "display: none" in the 

style attribute to maintain control over visibility in other media types than screen, most notably print. Default 

value: "tabs-hide".
tabStruct (String): A CSS selector or basic XPath expression reflecting a nested HTML structure that is different 

from the default single div structure (one div with an id inside the overall container holds one tab's content). If 

for instance an additional div is required to wrap up the several tab containers such a structure is expressed by 

"div>div". Default value: "div".
示例

说明:

Create a basic tab interface.

jQuery 代码:

$('#container').tabs();
说明:

Create a basic tab interface with the second tab initially activated.

jQuery 代码:

$('#container').tabs(2);
说明:

Create a tab interface with the third and fourth tab being disabled.

jQuery 代码:

$('#container').tabs({disabled: [3, 4]});
说明:

Create a tab interface that uses slide down/up animations for showing/hiding tab content upon tab switching.

jQuery 代码:

$('#container').tabs({fxSlide: true});

8.9.4 triggerTab(position)

Activate a tab programmatically with the given position (no zero-based index), as if the tab itself were clicked.

返回值

jQuery

参数

position (Number): An integer specifying the position of the tab (no zero-based index) to be activated. If this 

parameter is omitted, the first tab will be activated.
示例

说明:

Activate the second tab of the tab interface contained in <div id="container">.

jQuery 代码:

$('#container').triggerTab(2);
说明:

Activate the first tab of the tab interface contained in <div id="container">.

jQuery 代码:

$('#container').triggerTab(1);
说明:

Activate the first tab of the tab interface contained in <div id="container">.

jQuery 代码:

$('#container').triggerTab();

8.10 Tooltip
Tooltip(settings)

Display a customized tooltip instead of the default one for every selected element. The tooltip behaviour mimics 

the default one, but lets you style the tooltip and specify the delay before displaying it.

In addition, it displays the href value, if it is available.

To style the tooltip, use these selectors in your stylesheet:

#tooltip - The tooltip container

#tooltip h3 - The tooltip title

#tooltip p.body - The tooltip body, shown when using showBody

#tooltip p.url - The tooltip url, shown when using showURL

返回值

jQuery

参数

settings (Object): (optional) Customize your Tooltips
Hash 选项

delay (Number): The number of milliseconds before a tooltip is display, default is 250
event (String): The event on which the tooltip is displayed, default is "mouseover", "click" works fine, too
track (Boolean): If true, let the tooltip track the mousemovement, default is false
showURL (Boolean): If true, shows the href or src attribute within p.url, default is true
showBody (String): If specified, uses the String to split the title, displaying the first part in the h3 tag, all 

following in the p.body tag, separated with <br/>s, default is null
extraClass (String): If specified, adds the class to the tooltip helper, default is null
fixPNG (Boolean): If true, fixes transparent PNGs in IE, default is false
示例

说明:

Shows tooltips for anchors, inputs and images, if they have a title

jQuery 代码:

$('a, input, img').Tooltip();
说明:

Shows tooltips for labels with no delay, tracking mousemovement, displaying the tooltip when the label is clicked.

jQuery 代码:

$('label').Tooltip({ delay: 0, track: true, event: "click" });
说明:

This example starts with modifying the global settings, applying them to all following Tooltips; Afterwards, 

Tooltips for anchors with class pretty are created with an extra class for the Tooltip: "fancy" for anchors, 

"fancy-img" for images

jQuery 代码:

// modify global settings $.extend($.fn.Tooltip.defaults, { track: true, delay: 0, showURL: false, showBody: " - ", 

fixPNG: true }); // setup fancy tooltips $('a.pretty').Tooltip({ extraClass: "fancy" }); $('img.pretty').Tooltip({ 

extraClass: "fancy-img", });