My jQuery Notes
<1>Basic concepts
0. Dom elemenet => jQuery Wrapper:
function (menuTag, itemTag) {
var menu = $(menuTag).data("tMenu");
var item = $(itemTag, menu.element);
menu.enable(item);
var imgUrl = $("#h_imgSaveUrl").val();
$("#btnSaveSetup>span>img").attr("src", imgUrl);
}
|
1.jQuery Wrapper =>Dom element:
var divElement = $("#testDiv")[0];
|
2. this and $(this)
this is dom element, while $(this) is jquery wrapper
$("#testDiv").each(function(){ this.innerHTML = "I have added some text to an element."});
$("#testDiv").each(function(){ $(this).html("I have added some text to an element.")}
|
3. window.onload and $(document).ready()
window.onload is NOT recommented, because:
(1) waiting for the document fully loaded causes delay;
(2) could make the whole unobtrusive javascirpt not loaded
(3) wndow.onload can only run ONCE on the page while $(document).ready() can run multiple times(in the order of appearance)
4. making DOM element
| $("<p>Hello world<p>").insertAfter("#folloMe"); |
<2>Selectors and wrapped set
0. $("div, span") => selects all <div> and <span> elements
1. :first and :first-child ---- While :last matches only a single element, :last-child can match more than one: one for each parent.
2. attribute selector doesn't need quotation marks:
correct:
a[href ^= http: ] , input[type=text], div[title*=great]
|
| a[href ^= 'http://'] , input[type='text'], div[title*='great'] |
3. attribute selector can be multiple:
| input[title^=great][id][type=text] |
4. remember :eq is 0-based and :nth-child is 1-based
5. Filter selectors
- Categories:
(1) attribute
:button :checkbox :file :image :password :radio input[type=button] input[type=checkbox] input[type=file] input[type=image] input[type=password] input[type=radio] :reset :submit :text :header :input input[type=reset] input[type=submit] input[type=text] from<h1>to <h6> is input element
(2)status
:animated :checked :diabled :hidden :selected :visible (3)logical
:contains() :not(filter)
-
examples:
(1)combining filters:
$("div").has("input:checkbox:checked:enabled");(2) :not filter
$("input:not(:checkbox)")
note, :not filter can only apply to filter selectors, e.g, div p:not(:hidden) is valid, but div :not(p:hidden) is invalid because it attemps to apply :not to “p:hidden”, which is not filter selector
6. generate new html
e.g.
$("<div>Hello</div>").appendTo("#someParentDiv")$("<div>") -- identical to $("<div></div>") and $("</div>")
7. size() returns the count of elements in the wrapped set
$("div").size() -- equals to $("div").length
8. get(index) returns the Dom elements from a jQuery wrapped set
$("img[alt]").get(0) -- equals to $("img[alt]")[0]
9. index(element) returns the ordinal value, that is, the index within the wrapped set
<table> <tr> <td>123</td> <td></td> </tr> <tr> <td>abc</td> <td></td> </tr> </table>
var index = $("#tableStudent tr").index($("td:contains('abc')").closest("tr")[0]);index would be 1, which refers to the second row
10. not(expression) and filter(expression)
not(expression) ---- Exclude elements which match the criteria
filter(expression) ---- Keep elements which match the criteria
filter can use function as expression to perform the filter while not cannot
11. contains(text)
Attention: this command means find children elements which conains the text in their markup and attribute values, it doesn’t match markup or attribute values of original elements being tested.
<div id="divGreat"> wall <span>great</span> </div> <div id="divWall"> great <span>wall</span> </div>
$("div").contains("great");
will return the first div, rather than the second div, because the first div has a child <span> containing text “great”
12. is(selector)
To check if the Wrapped Set contains any element that matches the selector expression, e.g. var hasImage = $(‘*’).is(‘img’)
<3> Manipulating properties and attributes
0.jQuery functions
- each()
- attr(name), attr(name,value)
- removeAttr(name)
- addclass(names)
- removeClass(names)
- toggleClass(name)
- css(name,value)
- width()
- height()
- hasClass(name)
- html(), html(text)
- text(content)
- append(content)
- appendTo(target)
- prepend, prependTo
- before, inserBefore
- after, insertAfter
- wrap(wrapper)
- empty()
- remove()
- replaceWith()
- clone()
- end()
1. enable and disable element
As long as the element has the attribute “disabled”, no matter its value is, the state keeps disabled. To re-enable it, the way is to remove the “disabled” attribute:
Enable:
$("whatever").attr("disabled", "disabled");Disable:
$("whatever").removeAtt("disabled");
2. text()
Concatenates all text content of the wrapped elements and returns it
<ul id="theList"> <li>One</li> <li>Two</li> <li>Three</li> <li>Four</li> </ul>
the next expression will return OneTwoThreeFour
var text = $("#theList").text
3.text(content)
Unlike the
.html()method,.text()can be used in both XML and HTML documents.
The code
$('div.demo-container').text('<p>This is a test.</p>');will produce the following DOM output:<div class="demo-container"> <p>This is a test.</p> </div>It will appear on a rendered page as though the tags were exposed, like this:
<p>This is a test</p>
4.Ways to get individual element from jQuery set
- using array index on the wrapped set: $(foo)[n]
- using get() or toArray() metho
- using each() or map()
- using eq() or :eq filter
5. appendTo(target)
target > 1 => copy to each target’s content
target = 1 => move to this target
6. before() and after()
Insert element before / after the target element, not inside the target’s content like append / prepend
7. wrap(wrapper)
- To add a <div> outside the link
$("a.insideLink").wrap("<div class='hello'></div>");
- To wrap the link with a clone of other <div> in the current page
$("a.insideLink").wrap($("div.hello:first")[0]);
8. empty() and remove()
- empty() is to remove the content of the element
- remove() is to remove the element itself, of course including its content
9. replaceWith()
$("div.elementToReplace").replaceWith("<p> I am replacing the div </p>");
<4> Events
0.jQuery functions
- bind()
- one()
- unbind()
- trigger(eventType)
- eventName()
- toggle(listenerOdd,listenerEven)
- hover(overListener,outListener)
1. bind(eventType, data, listener)
- Note: data is a caller-supplied data that’s attached to eh event instance as a property named data for availability to the handler function, actually it is an an object that is put into the context of the listener function, this object’s name is “data”.
$("#foo").bind("click", { msg: "spoon" }, function (event) { alert(event.data.msg) });
- Remember, put an unbind before bind an event to make sure only ONE handler is bound to that event
$("#foo").unbind("click").bind("click", function () { alert("unbind before bind to make sure single binding") });
2. eventTypeName(listener)
we can use shortcuts instead of using bind():
$("#foo").bind("click", function () { alert("using bind() function to bind click event") }); $("#foo").click(function () { alert("using shortcut to bind click event") });
Note that when using these shortcut methods, we CANNOT specify a data value to be placed in the event.data property.
3. one (eventType, data, listener)
Once the handler function executed, the handler function is automatically removed, that means, the handler function will be only triggered once.
4. Trigger event handler
- trigger(eventType)
$("#foo").trigger("click");
- eventName
$("#foo").click();
- toggle(listenerOdd,listenerEven)
A pair of click event handlers that swap off with each other on every other click event.
<5> Animation and Effects
0.jQuery functions
- hide(speed,callback)
- show(speed,callback)
- toggle(speed,callback)
- fadeIn(speed,callback)
- fadeOut(speed,callback)
- fateTo(speed,opacity,callback)
- sildeDown(speed,callback)
- sildeUp(speed,callback)
- sildeToggle(speed,callback)
- stop()
- animate()
1.Always use jQuery hide() and show() to change the visibility of element, not to use style attributes
2.Use toggle() to swap the displayed state.
<6> jQuery Utilities
0.
1.jQuery flags
- $.fx.off ---- Enable or disable animations (true: disable, false: enable)
- $.support ---- Details supported features
- $.browser ---- Exporse browser details
2. $.noconflict(jqueryToo)
Gives up the “$” identifier while using other libralies with jQuery. This method should be called after including jQuery but before including the conflicting library.
After giving up “$” idenitfier, “jQuery” should be used instead.
3. Isolate the “$” identifier in a function
(function($){ /* function body here */}) (jQuery)
Here, (function($){ /* function body here */}) is a function, let’s say, fn. And “jQuery” is the parameter, so the expression comes out to be fn(jQuery).
In this way, in our function, “$” is “jQuery”, any EXTERNAL declaration of “$” is different from the “$” inside this function.
4. trim(value)
Removes any leading or trailing whitespace characters from the passed string and returns the result.
5. $.each(container,function(index,value){})
Note that when iterating over an array or object, we can break out of the loop by “return false” from the iterator function. That means, “return false” equals “break”
Note, the performance: for loop > each() > $.each()
6. Filtering array
$.grep(array,function, invert)
var bigMembers = $.grep(originalArray, function (value) { return value > 100; })var bigMembers = $.grep(originalArray, function(value){ return value > 100;})
7. Translating array
var onBasedArray = $.map([0, 1, 2, 3, 4, 5], function (value) { return value + 1 });and onBasedArray is [1, 2, 3, 4, 5, 6]
8. $.inArray(value,array)
Returns the index position of the first occurence of the passed value.
9. $.makeArray(object)
Converts the passed array-like object into a Javascript array
10. $.unique(array)
Given an array of DOM elements, returns an array of unique elements in the original array.
Note that this function only works for DOM element array
11. $.merge(arrayy1,array2)
var array1 = [1, 2, 3, 4, 5]; var array2 = [6, 7, 8, 9, 0]; $.merge(array1, array2);array1 becomes [1, 2, 3, 4, 5, 6, 7, 8, 9, 0], and array2 is untouched.
12. $.param(params,traditional)
Encode the passed information into a string suitable for use as the query string of a sbumitted request.
var myObject = { a: { one: 1, two: 2, three: 3 }, b: [1, 2, 3] }; var recursiveEncoded = $.param(myObject); var recursiveDecoded = decodeURIComponent($.param(myObject));
The values of
recursiveEncodedandrecursiveDecodedare alerted as follows:a%5Bone%5D=1&a%5Btwo%5D=2&a%5Bthree%5D=3&b%5B%5D=1&b%5B%5D=2&b%5B%5D=3
a[one]=1&a[two]=2&a[three]=3&b[]=1&b[]=2&b[]=3
A more complicated exmaple
var param = $.param({ "a thing": "it&s=value", "another thing:": "another value", "weird characters": "@@#$^&()_+=" })
13.$.noop()
Does nothing. It serves as a handy default for those callbacks when the user does not supply one.
14. $.contains(container, containee)
Similar to has() method, but it work against DOM element, rather than wrapped set.
15. $.proxy(function, contextObj)
Assign a DOM element or javascirpt object to the function as it’s context
<div id="divGreat"> wall <span id="spanGreat">great</span> </div>
$("#spanGreat").click(function(){ alert(this.id); }) shows "spandGreat" $("#divGreat").click(function(){ $.proxy(alert(this.id), $("#divGreat")[0]); }) shows "divGreat"
The most common use case for $.proxy is when we wan to bind a method of an object as a handler, and have the method’s owning object established as the handler’s function context exactly as if we had called the method directly.
var obj = { id: "objId", hello: function () { alert("Hi there! I'm" + this.id); } };
$(whatever).click($.proxy(obj.hello, obj));
16. $.getScript(url, callback)
Load the script specified bye the url parameter. The callback function is useful when it’s necessary to make sure the function in callback run after the script is loaded.
<7>AJAX
1. load(url,parameters,callback)
Load data from the server and place the returned HTML into the matched element.
$('#result').load('ajax/test.html', function () { alert('Load was performed.'); });
2. serialize()
Encode a set of form elements as a string for submission.
Note, it will igore : unchecked chekbox, unchecked radiobutton, unselected dropdown and disabled controls
It’s handy to submit form elements with ajax by using serialize():
var url = applicationRoot + '/GradeBook/SaveSetupInfo'; $.ajax({ url: url, type: "POST", dataType: "text", data: $("#formSaveSetup").serialize(), success: function (result) { PageFunction.EnableSaveButton(false); }, error: function (result) { alert("Unable to save setup!"); } });
3. $.get() and $.post()
Note, a GET request should be used whenever the purpose of the request is to merely get data. When data is being sent to the server in order to effect a change, POST should be used.
4. Avoid caching
By default, the ajax response is cached by the browser. Add cache: false to ajax command will avoid that caching.
5. Access elements in an iframe
Example: $("#iframeID").contents().find('div#header').hide();

浙公网安备 33010602011771号