JQuery 1.4:15 new features and optimization enhancements

Source: Internet
Author: User
Tags filter object bind config functions new features numeric value pear

JQuery 1.4 has recently been released . Beyond everyone's expectations, this is not a simple tinkering, 1.4 contains a lot of new features, enhancements and performance improvements! This article introduces you to these new features and enhancements that might be useful to you.

You can download the jquery 1.4 trial immediately: http://code.jquery.com/jquery-1.4.js

1. Pass to JQuery (...)

Before, jquery can set the attributes of an attr element by means of both the name and the value of the property, or an object that contains several sets of specific property name value pairs. In jquery 1.4, you can pass a parameter object as the second argument to the JQuery function itself, creating HTML elements as well.

Let's say you want to create an anchor element () with several attributes. In 1.4, it was all so simple:

JQuery ('  ', {
ID: ' foo ',
HREF: ' http://google.com ',
Title: ' Become a Googler ',
Rel: ' External ',
Text: ' Go to google! '
});

As you can probably guess, this anchor element does not have a text property that invokes the JQuery private method " .text() ", and the text in the element is set to google!.

For this usage, the following are more useful examples:

JQuery (' 
   
', {
ID: ' foo ',
CSS: {
fontweight:700,
Color: ' Green '
},
Click:function () {
Alert (' Foo has been clicked! ');
}
});

The ID is a generic attribute and is added directly, while the CSS and click triggers the corresponding JQuery method. Before 1.4, the code above should be written like this:

JQuery (' 
    
')
. attr (' id ', ' foo ')
. css ({
fontweight:700,
Color: ' Green '
})
. Click (function () {
Alert (' Foo has been clicked! ');
});

Learn more about JQuery (...)

2. Until I met you ...

3 new methods are added to the DOM Traversal Toolkit for 1.4: nextUntil, prevUntil and parentsUntil . These methods traverse the DOM in a specific direction until the element that satisfies the specified selector is encountered. For example, now we have a list of fruit names:

     

  • Apple


  • Banana

  • Grape


  • Strawberry

  • Pear


  • Peach

We want to pick out all the entries in Apple before Pear. The code is simple:

JQuery (' ul li:contains (Apple) '). Nextuntil (': Contains (Pear) ');
It's Banana, Grape, Strawberry.

Learn more: prevuntil, nextuntil, parentsuntil

3. Bind multiple event handlers

You no longer need to bind the various event-binding methods together, and now you can bundle them into a bunch, as follows:

JQuery (' #foo). Bind ({
Click:function () {
Do something
},
Mouseover:function () {
Do something
},
Mouseout:function () {
Do something
}
})

This usage also applies to " .one() ".

Learn more about. Bind (...)

4. Specify the easing effect according to the attribute

You can only specify a slow effect (easing, the speed change rule in the animation process) for only one animation before. JQuery native supports two easing effects, swing (default) and linear. To use other effects, you will need to download them separately . , you can now specify different easing effects for each property parameter of the animation:

JQuery (' #foo '). Animate ({
LEFT:500,
Top: [, ' Easeoutbounce ']
}, 2000);

Click here to see the actual effect

You can also set a series of name-value pairs for secialeasing in an optional Animation option object:

JQuery (' #foo '). Animate ({
LEFT:500,
top:500
}, {
duration:2000,
Specialeasing: {
Top: ' Easeoutbounce '
}
});

Editor's note: Our author James Padolsey is modest, this function point is he thought out Oh!

Learn more about the per-property-easing content

5. Updated Live Events!

JQuery 1.4 adds support for assigning submit , change, focus, and blur events. In jquery, we use the .live() method to assign events. This is useful when you want to register event handlers for multiple elements. And even if the elements that satisfy the selector are new, these events will continue to work (using more .live() effort than the repeated bindings).

but watch out! you need to use focusin and focusout as event names when registering focus and Blur events.

JQuery (' input '). Live (' Focusin ', function () {
Do something and this
});

6. Control function Context

jquery 1.4 provides a completely new proxy function, located under the jquery namespace. This function accepts two parameters, one is "scope" or one method name, and the other is a function or target scope (the intended scope).

As we all know, the This keyword of JavaScript is a difficult thing to grasp. Sometimes you don't want it to represent an element, but you want it to represent an object that you created earlier.

For example, here we created an app object that has two properties, one is a clickHandler method, and one is the object responsible for the parameter configuration.

var app = {
Config: {
Clickmessage: ' hi! '
},
Clickhandler:function () {
alert (this.config.clickMessage);
}
};

This clickHandler method, when app.clickHandler() invoked like this, app is its context, which means that this the keyword is pointing to app . This is no problem if you simply invoke it:

App.clickhandler (); "Hi!" is alerted

But if you think of it as an event handler:

JQuery (' a '). bind (' click ', App.clickhandler);

When we click on this anchor, we do not have the desired result (nothing alert). This is because jQuery (and most sensible event models), by default, will specify the context of the processor as the target element itself. Other wordsthis 所代表正是被点击的这个链接。而我们想的是,this 应该继续代表 app 。在jQuery 1.4中,实现这一目的十分简单:

JQuery (' a '). Bind (
' Click ',
Jquery.proxy (app, ' ClickHandler ')
);

Now click on all the anchors will pop up "hi!" Out.

The surrogate function wraps your function around the same time, and sets the function inside it this to what you want. Proxy functions can also be useful in other contexts, such as passing callback functions to other jQuery methods or Plug-ins.

Learn MorejQuery.proxy

7. Animation Queue delay

Now, you can add a delay to the animation queue. Although this feature can be implemented in any queue, the most common possibility is to delay the "FX queue" (the "FX" queue,jquery default animation queue). It allows you to pause between two animation behaviors without having to involve a callback function or setTimeout something like that. .delay()The first parameter that you need to set is the number of milliseconds to delay:

JQuery (' #foo ')
. Slidedown ()//Slide down
. delay//Do No for MS
. FadeIn (); Fade in

If you want to delay a queue other than FX, pass the queue name as the second argument .delay() 就可以了 .

Learn More.delay(…)

8. Detect whether the element contains specific content

JQuery 1.4 makes it easier to detect whether an element (or set) contains ( .has() ) something. The mechanism behind it is the same as :has() the selection filter. This method selects elements from the current collection that satisfy one of the specified conditions.

JQuery (' div '). has (' ul ');

This statement picks up those containing the UL elements in all DIV elements. This may be a good time to choose a filter :has() , but the method is useful when you want to filter the selection set more programmatically .has() .

jquery 1.4 also adds a function to the jquery namespace contains . This is a relatively low-level function that accepts two DOM nodes as parameters. Returns a Boolean value that indicates whether the second element is contained in the first element. For example:

Jquery.contains (Document.documentelement, document.body);
Returns true- is indeed included in

Message Understanding: .has(…) ,jQuery.contains(…)

9. Peel the Elements!

A long time ago, jQuery can be used .wrap() to give the yuan a layer of skin. Now, JQuery 1.4 adds a .unwrap() method for skinning. Look at the following DOM structure:

                  

Foo


To peel off a layer of skin (div) outside the P element:

JQuery (' P '). Unwrap ();

The DOM becomes:

Foo

In summary, this method removes the parent element of any element.

Learn More.unwrap(…)

10. Remove elements without deleting the data

Previously there .remove() was a method of stripping the elements and discarding them. The new .detach() approach allows you to strip an element from the DOM without losing data. The JQuery object that contains the element retains the element after the operation completes. The data can be passed into .data() the jquery object through any event handler in the jquery event system.

This function can be useful when you need to remove an element from the DOM and then reintroduce it in a future scenario. The event handle of the element and all other data are preserved.

var foo = jQuery (' #foo ');

To bind an important event handler
Foo.click (function () {
Alert (' foo! ');
});

Foo.detach (); removing from the DOM
.. do stuff

Foo.appendto (' body '); Rejoin to Dom

Foo.click (); Pop-up alert information: "Foo!"

Learn More.detach(…)

Enhancements to index (...)

JQuery 1.4 .index() provides two new ways for you to use. Previously, you had to pass the element to it as a parameter and then get a return value that represents the index of the element in the current collection. Now, if the argument is not passed, the returned value represents the number of elements that are ranked among their peers. Let's say the following DOM:

                      

  • Apple


  • Banana

  • Grape


  • Strawberry

  • Pear


  • Peach

You want to know when you click on an entry, it is the first of the list, and the code you implement is very simple:

JQuery (' Li '). Click (function () {
Alert (JQuery (this). index ());
});

JQuery 1.4 also allows you to take the selector as .index() the first argument. Doing so returns the index value of the current element in the collection of elements that are matched by the selector you specify.

It's also important to note that this method returns a numeric value that returns a value of 1 if an element of the specified condition cannot be found in the document.

Learn More.index(…)

DOM manipulation can receive callback functions

Most DOM manipulation methods now support passing functions as a single parameter ( .css() and passing in as the .attr() second parameter). This function runs through each element of the selection set, providing a more "personalized" value for the corresponding manipulation method.

The following methods support this feature:

    • After
    • before
    • Append
    • prepend
    • AddClass
    • Toggleclass
    • Removeclass
    • Wrap
    • Wrapall
    • Wrapinner
    • Val
    • text
    • replacewith
    • CSS
    • attr
    • HTML

With the callback function, you can access the current element using the keyword in the selection set this , and call the index value with the first argument of the callback function.

JQuery (' li '). html (function (i) {
Return ' Index to this list item: ' + i;
});

Also, some of the above methods provide a second parameter for you to use. .html()You can also get the current value if you are calling a setting method (such as and .attr('href...) ). For example:

JQuery (' a '). attr (' href ', function (i, currenthref) {
return currenthref + ' Foo=bar ';

As you can see, for .css() and .attr() method, the function is passed as a second argument because the first argument is used to specify which property we need to modify:

JQuery (' Li '). css (' Color ', function (i, Currentcsscolor) {
Return I% 2? ' Red ': ' Blue ';
});

13. Decision Object Type

jquery 1.4 has added two new auxiliary functions (all directly under the JQuery namespace) to help you identify which object you are manipulating.

The first function, which isEmptyObject returns a Boolean value, determines whether the object is empty (). The second is isPlainObject that the Boolean value it returns represents a simple object (plain object) that {} 或 new Object() passes past arguments whether it is JavaScript.

Jquery.isemptyobject ({}); True
Jquery.isemptyobject ({foo:1}); False

Jquery.isplainobject ({}); True

Jquery.isplainobject (JQuery ()); False

Learn more: isPlainObject(…) ,isEmptyObject(…)

Enhancements to closest (...)

The jquery .closest() method can now accept a set of selectors as parameters. This feature can be useful when you need to traverse all the superiors of an element to find more than one recent element that matches a particular feature.

Also, it can now accept the context as a second parameter, which means you can control the depth or distance of the DOM traversal. While it may be rare to use these two new features, the effect is amazing!

Learn More.closest(…)

15. New Events! Focusin and Focusout

As mentioned earlier, when you deploy focus and blur events, you need to use the two new events of Focusin and Focusout. These two events help you take action when a particular element or element's child element gets/loses focus.

JQuery (' form ')
. Focusin (function () {
JQuery (This). AddClass (' focused ');
});
. Focusout (function () {
JQuery (This). Removeclass (' focused ');
});

It is worth noting that these two events do not spread (that is, the so-called "bubbling"), they will be caught. That is, the external elements (parents) are triggered before the "target" element of the Evil (causal).

Learn more about focusIn and focusOut event content.

Love JQuery 1.4! The history of the most thoughtful, feature the most rich, performance of the best jQuery!

That's it... I've already introduced some of the new features that I think are most influential to you.

If you don't know, go and check out the "Days ofjquery" event, a fantastic online event to celebrate the release of jquery 1.4 and the four birthday of jquery. Show you use JQuery to write the proud, to win MediaTemple a year of host use!

Also, don't take a look at the new API documentation !

Original Author:James Padolsey

Original address:http://net.tutsplus.com/tutorials/javascript-ajax/jquery-1-4-released-the-15-new-features-you-must-know/

Reprint needs to retain the source.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.