Friday, October 28, 2011

JQuery New Feature

Passing Attributes to jQuery(…)

Pre 1.4, jQuery supported adding attributes to an element collection via the useful "attr" method, which can be passed both an attribute name and value, or an object specifying several attributes. jQuery 1.4 adds support for passing an attributes object as the second argument to the jQuery function itself, upon element creation.

Let’s say you need to create an anchor element with several attributes. With 1.4 it’s as simple as:

You may have noticed the "text" attribute— you’ll probably be wondering what that’s doing there, after all there’s no "text" attribute for anchors! Well, jQuery 1.4 utilises its very own methods when you pass certain attributes. So the “text” attribute specified above would cause jQuery to call the ".text()" method, passing "Go to Google!" as its only argument.

A better example of this in action:

  1. jQuery('
    ', {
  2. id: 'foo',
  3. css: {
  4. fontWeight: 700,
  5. color: 'green'
  6. },
  7. click: function(){
  8. alert('Foo has been clicked!');
  9. }
  10. });

The "id" is added as a regular attribute, but the "css" and "click" properties trigger calling of each respective method. The above code, before the 1.4 release, would have been written like this:

  1. jQuery('
    ')
  2. .attr('id', 'foo')
  3. .css({
  4. fontWeight: 700,
  5. color: 'green'
  6. })
  7. .click(function(){
  8. alert('Foo has been clicked!');
  9. });

No comments:

Post a Comment