2009年11月24日 星期二

[jquery] 工具的使用.

出處:


 $.trim(value)
In dealing with strings, JavaScript already has quite a comprehensive set of functions, such as split, substr, charAt (see references at http://www.w3schools.com/jsref/jsref_obj_string.asp), however, for some mysterious reasons, it does not have a trim function for ridding of leading and trailing white space. Smart and generous people have contributed to the web various versions of their trim functions. Such as:

var trimmed = str.replace(/^\s+|\s+$/g, '') ;
It works perfectly. However, how about simply call trim() function provided by JQuery? The syntax is $.trim(value)
var trimmed = $.trim(" this really needs to be trimmed ");
Clean and plain English, right?
Array functions:

$.each (container, callback)

In JQery, in addition to the conventional JavaScript array (array of strings, numerics, elements), there is also specifically object array in the form of key-value pairs.

The former array is coded as:
var arr = [ "one", "two", "three", "four", "five" ];
 The later (each pair seperated by a colon :) :
var obj = { item1: "one", item2: "two" ,item3: "three", item4: "four"};
It has always been easy to loop through an JavaScript array. However, it can be easier with the JQuery $.each function. The syntax is
$.each (container, callback). The callback function receives two arguments with the passing of each element: with [] type (traditional JavaScript) array, index and value; with {} type (array of objects with properties), key and value.

So we can access JQuery array elements as such (forgive me for using so many alerts):
 

$.grep (array, callback, invert)

JQuery offers a $.grep() function to return an array of elements that matches a certain condition. The callback function is passed two parameters: the current value and its index. For example,
 

$.map (array, callback)

One convenient function to transform all of the elements in an array in one shot. Change a string array into a numeric array? Yes; Change the numeric array back to a string array? Yes; Add a 10 to every number in an array? Yes. Just call the $.map function.

For example:
 

Other extremely useful JQuery array functions are:

$.inArray(value, array), returns the position of the first occurance of the element by a specified value. As in:

$.unique(array), returns a deduplicated array. As in:

$.makeArray(object), create an array out of a selected elements. As in:


$.extend(target, source1, source2, ... sourceN), extends the target object with the properties of the sources. For example:
  
 

【下列文章您可能也有興趣】

沒有留言: