Jquery 1.4 released: 15 new feature instances

Source: Internet
Author: User
Jquery 1.4 has recently been released. Beyond everyone's expectation, this is not a simple repair and supplement, 1.4 includes ManyNew features, feature enhancements, and performance improvements! This article describes the new features and optimization enhancements that may be useful to you.

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

1. Pass the parameter to jquery (...)

Previously, jquery could use the ATTR method to set the attributes of an element. It can either pass the attribute name and value, or it can be an object that contains several sets of specific attribute name and value pairs. In jquery 1.4, you can pass a parameter object as the second parameter to the jquery function itself and Create HTML elements.

For example, you want to create an anchor element with several attributes (<A> </a> ). In 1.4, everything is so simple:Copy content to clipboard
Code:

jQuery('<a/>', {
    id: 'foo',
    href: 'http://google.com',
    title: 'Become a Googler',
    rel: 'external',
    text: 'Go to Google!'
});

You can probably guess that the text attribute not available for this anchor element will call jquery's private method. Text () and set the text in the element to "go to Google !"

For this usage, the following is a more useful example:Copy content to clipboard
Code:

jQuery('<div/>', {
    id: 'foo',
    css: {
        fontWeight: 700,
        color: 'green'
    },
    click: function(){
        alert('Foo has been clicked!');
    }
});

ID is a general attribute and is directly added, while CSS and click inspire the corresponding jquery method. Before 1.4, the above Code should be written as follows:Copy content to clipboard
Code:

jQuery('<div/>')
    .attr('id', 'foo')
    .css({
        fontWeight: 700,
        color: 'green'
    })
    .click(function(){
        alert('Foo has been clicked!');
    });

Learn more about jquery (...)

2. Wait until you meet you...

In the 1.4 Dom traversal toolkit, three new methods are added: nextuntil, prevuntil, and parentsuntil. These methods traverse the DOM in a specific direction until the elements that meet the specified selector are met. For example, we have a list of fruit names:Copy content to clipboard
Code:

<ul>
    <li>Apple</li>
    <li>Banana</li>
    <li>Grape</li>
    <li>Strawberry</li>
    <li>Pear</li>
    <li>Peach</li>
</ul>

We want to select all entries before Apple and pear. The code is very simple:Copy content to clipboard
Code:

Jquery ('ul Li: Contains (Apple) '). nextuntil (': Contains (PEAR )');
// Select banana, grape, and strawberry.

For more information, see prevuntil, nextuntil, and parentsuntil.

3. bind multiple event Processors

You no longer need to chain events together. Now you can bundle them into a pile, as shown below:Copy content to clipboard
Code:

jQuery('#foo).bind({
    click: function() {
        // do something
    },
    mouseover: function() {
        // do something
    },
    mouseout: function() {
        // do something
    }
})

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

For more information, see. BIND (...)

4. Specify the easing Effect Based on the attribute

In the past, only one easing effect (easing) can be specified for an animation. Jquery native supports two easing effects: Swing (default) and linear. To use other effects, you need to download them separately .), Now you can specify different easing effects for each attribute parameter of the animation:Copy content to clipboard
Code:

jQuery('#foo').animate({
    left: 500,
    top: [500, 'easeOutBounce']
}, 2000);

Click here to view the actual results

You can also set a series of name-value pairs for secialeasing in an optional animation option object to complete the above work:Copy content to clipboard
Code:

jQuery('#foo').animate({
    left: 500,
    top: 500
}, {
    duration: 2000,
    specialEasing: {
        top: 'easeOutBounce'
    }
});

Edit Note: James padolsey, our author, is modest. He came up with this feature!

Learn more about per-property-easing

5. Updated live events!

Jquery 1.4 adds an assignmentSubmit,Change,FocusAndBlurEvent support. In jquery, we use the ". Live ()" method to assign events. This is useful when you want to register event processors for multiple elements. And even if the elements that meet the selection operator are new, these events will continue to work (using. Live () is much easier than repeatedly binding ).

But be careful!You need to useFocusinAndFocusoutAs the event name.Copy content to clipboard
Code:

jQuery('input').live('focusin', function(){
    // do something with this
});

6. Control Function Context

Jquery 1.4 provides a new proxy function located in the jquery namespace. This function accepts two parameters: scope or method, and intended scope ).

As we all know, this keyword in Javascript is hard to grasp. Sometimes you don't want it to represent an element, but want it to represent an object you created earlier.

For example, here we create an app object, which has two attributes: clickhandler method and parameter configuration object.Copy content to clipboard
Code:

var app = {
    config: {
        clickMessage: 'Hi!'
    },
    clickHandler: function() {
        alert(this.config.clickMessage);
    }
};

This clickhandler method, when called like app. clickhandler (), the app is its context, that is, the keyword this points to the app. If you just need to call it, there is no problem in writing this statement:Copy content to clipboard
Code:

app.clickHandler(); // "Hi!" is alerted

However, if we treat it as an event processor:Copy content to clipboard
Code:

jQuery('a').bind('click', app.clickHandler);

When we click this anchor, the expected effect is not achieved (nothing alert is available ). This is because jquery (and most rational event models) specifies the context of the processor as the target element by default. That is to say, this indicates the clicked link. What we think is that this should continue to represent the app. In jquery 1.4, this goal is very simple:Copy content to clipboard
Code:

jQuery('a').bind(
    'click',
    jQuery.proxy(app, 'clickHandler')
);

Now, "Hi!" will pop up when you click all the anchors !" .

The proxy function wraps your function in a circle and sets this in the function to what you want. In other context application scenarios, such as passing callback functions to other jquery methods or plug-ins, proxy functions can also be used.

Learn more about jquery. Proxy

7. animation queue delay

Now, you can add a delay to the animation queue. Although this function can be implemented in any queue, the most common function is to delay the "FX queue" ("FX" queue, jquery's default animation Queue ). It allows you to pause between two animation actions, instead of involving callback functions and setTimeout. The first parameter of. Delay () is the number of milliseconds you need to set:Copy content to clipboard
Code:

jQuery('#foo')
    .slideDown() // Slide down
    .delay(200) // Do nothing for 200 ms
    .fadeIn(); // Fade in

If you want to delay a queue other than FX, pass the queue name as the second parameter to. Delay.

Learn more about. Delay (...)

8. Check whether the element contains specific content.

Jquery 1.4 makes it easier to check whether an element (or set) contains something (. Has. The mechanism behind it is the same as the selection filter: Has. This method selects elements that meet any specified condition from the current set.Copy content to clipboard
Code:

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

This statement Selects all DIV elements that contain ul. In this case, you may use the selection filter: Has (), but the. Has () method is very useful when you want to filter the selection set more programmatically.

Jquery 1.4 also adds a contains function in the jquery namespace. This is a relatively underlying function that accepts two DOM nodes as parameters. Returns a Boolean value indicating whether the second element is contained in the first element. For example:Copy content to clipboard
Code:

Jquery.contains(document.doc umentelement, document. Body );
// Return true-<body> indeed included in <HTML>

Message understanding:. Has (...) , Jquery. Contains (...)

9. Peel the element!

Jquery has long been able to wrap an element with. Wrap. Now, the. Unwrap () method is added to jquery 1.4 for skin peeling. See the following Dom structure:Copy content to clipboard
Code:

<div>
    <p>Foo</p>
</div>

To remove a layer of skin (DIV) outside the P element:Copy content to clipboard
Code:

jQuery('p').unwrap();

Dom becomes:Copy content to clipboard
Code:

<p>Foo</p>

All in all, this method can remove the parent element of any element ..

Learn more about. Unwrap (...)

10. Remove elements without deleting data

In the past, A. Remove () method was used to strip elements and discard them. Brand new. Detach ()This method allows you to strip an element from the DOM without losing data. The jquery object that includes this element will retain this element after the operation is complete. Data can be transmitted to the jquery object through any event processor in the. Data () or jquery Event System.

This function is useful when you need to remove an element from the Dom and re-introduce it in a future scenario. The event handle of the element and all other data are retained.Copy content to clipboard
Code:

VaR Foo = jquery ('# foo ');
// Bind an important event Processor
Foo. Click (function (){
Alert ('foo! ');
});
Foo. Detach (); // remove from Dom
//... Do stuff
Foo. appendto ('body'); // re-add to Dom
Foo. Click (); // The alert message is displayed: "foo! "

For more information, see. Detach (...)

11. Index (...) Function enhancements

Jquery 1.4 provides two new methods for using. Index. In the past, you had to pass the element as a parameter to it and then get a returned value, representing the index of the element in the current set. Now, if you do not pass the parameter, the returned value indicates that an element ranks the same among its peers. For example, the following DOM:Copy content to clipboard
Code:

<ul>
    <li>Apple</li>
    <li>Banana</li>
    <li>Grape</li>
    <li>Strawberry</li>
    <li>Pear</li>
    <li>Peach</li>
</ul>

You want to know the first entry in the list after clicking an entry. The implementation code is very simple:Copy content to clipboard
Code:

jQuery('li').click(function(){
    alert( jQuery(this).index() );
});

Jquery 1.4 also allows you to use the selector as the first parameter of. Index. In this case, the index value of the element set matched by the current element in the selected element is returned.

Note that this method returns a value. If the element of the specified condition cannot be found in the document, a value of-1 is returned.

For more information, see. Index (...)

12. Dom manipulation can receive callback Functions

Currently, most Dom manipulation methods support passing functions as a single parameter (. CSS () and. ATTR () as the second parameter ). This function will run every element in the selection set, providing a more "personalized" value for the corresponding manipulation method.

The following methods support this function:

  • After
  • Before
  • Append
  • Prepend
  • Addclass
  • Toggleclass
  • Removeclass
  • Wrap
  • Wrapall
  • Wrapinner
  • Val
  • Text
  • Replacewith
  • CSS
  • ATTR
  • Html

      With the callback function, you can use the this keyword in the selection set to access the current element, and use the first parameter of the callback function to access its index value.Copy content to clipboard
      Code:

      jQuery('li').html(function(i){
          return 'Index of this list item: ' + i;
      });

      Also, some of the methods above provide the second parameter for your use. If you call a set method (such as. html () and. ATTR ('href...), you can obtain the current value. For example:Copy content to clipboard
      Code:

      jQuery('a').attr('href', function(i, currentHref){
          return currentHref + '?foo=bar';
      });

      As you can see,. CSS () and. for the ATTR () method, the function must be passed as the second parameter because the first parameter is used to specify which attribute we need to modify:Copy content to clipboard
      Code:

      jQuery('li').css('color', function(i, currentCssColor){
          return i % 2 ? 'red' : 'blue';
      });

      13. Determine the object type

      Jquery 1.4 adds two new auxiliary functions (both directly under the jquery namespace) to help you identify the objects you are manipulating.

      The first function is isemptyobject, which returns a Boolean value to determine whether the object is empty (). The second is isplainobject. The Boolean value returned by isplainobject indicates whether the previous parameter is a javascript simple object (plain object), that is, the object created with {} or new object.Copy content to clipboard
      Code:

      jQuery.isEmptyObject({}); // true
      jQuery.isEmptyObject({foo:1}); // false
      jQuery.isPlainObject({}); // true
      jQuery.isPlainObject(window); // false
      jQuery.isPlainObject(jQuery()); // false

      Learn more: isplainobject (...) , Isemptyobject (...)

      14. Closest (...) Function enhancements

      Jquery's. Closest () method can now accept a set of delimiters as parameters. When you need to traverse all the superiors of an element, findMore than oneThis feature is useful when it comes to the most recent elements that match specific features.

      Now, it can accept the context as the second parameter, that is, you can control the depth or extensiveness of Dom traversal. Although you may rarely use these two new features, the results will be amazing!

      Learn more. Closest (...)

      15. New events! Focusin and focusout

      As mentioned above, when deploying the focus and blur events, you need to use the focusin and focusout events. These two events help you to take actions when a specific element or its child element gets or loses focus.Copy content to clipboard
      Code:

      jQuery('form')
          .focusin(function(){
              jQuery(this).addClass('focused');
          });
          .focusout(function(){
              jQuery(this).removeClass('focused');
          });

      It is worth noting that these two events will not spread (that is, the so-called "bubble") and they will be captured. That is to say, the external element (parent) will be triggered before the "target" element.

      Learn more about focusin and focusout events.

      Fall in love with jquery 1.4! Jquery, which has the most thoughtful, function-rich, and performance in history!

      That's it... I have already introduced some of the new features that affect you the most.

      If you do not know, hurry up and see"14 days of jquery"Event, a great online activity to celebrate the release of jquery 1.4 and jquery's 4-year-old birthday. Show your interest in using jquery and win mediatemple's one-year host use right!

      In addition, don't take a look at the brand newAPI documentation! Reference:

      Author: James padolsey
      Original article from peide: jquery 1.4 release: 15 new feature instances
      Http://net.tutsplus.com/tutorials/javascript-ajax/jquery-1-4-released-the-15-new-features-you-must-know/

      The source must be retained for reprinting.

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.