Difference between revisions of "AJAX&Jquery"

From Hawk Wiki
Jump to: navigation, search
(Jquery Data & Attribute)
(Jquery Data & Attribute)
Line 47: Line 47:
 
keyA string naming the piece of data to set.
 
keyA string naming the piece of data to set.
 
valueThe new data value; it can be any Javascript type including Array or Object.
 
valueThe new data value; it can be any Javascript type including Array or Object.
 +
 
.attr( attributeName, value )
 
.attr( attributeName, value )
 
attributeNameThe name of the attribute to set.
 
attributeNameThe name of the attribute to set.
 
valueA value to set for the attribute.(string)
 
valueA value to set for the attribute.(string)
 
</pre>
 
</pre>

Revision as of 02:51, 3 April 2012

JavaScript

Closure.

<script>
function say667() {
  // Local variable that ends up within closure
  var num = 666;
  
  //var sayAlert = function() { alert(num); }
  return function() { num++; alert(num); };
}

var sayNumba = say667();
sayNumba();
sayNumba();
</script>

The example will keep var num in the memory. alert 667 and 668 on each call;

Jquery Data & Attribute

Attribute does not change when using .data

<a id="foo" data-foo="bar" href="#">foo!</a>
The data can then be accessed using .data() in jQuery:

console.log( $('#foo').data('foo') );
//outputs "bar"
However when you store data on a DOM node in jQuery using data, the variables are stored in on the node object. This is to accommodate complex objects and references as storing the data on the node element as an attribute will only accommodate string values.

continuing my example from above:

$('#foo').data('foo', 'baz');

console.log( $('#foo').attr('data-foo') );
//outputs "bar" as the attribute was never changed

console.log( $('#foo').data('foo') );
//outputs "baz" as the value has been updated on the object
Also, the naming convention for data attributes has a bit of a hidden "gotcha":

<a id="bar" data-foo-bar-baz="fizz-buzz" href="#">fizz buzz!</a>
console.log( $('#bar').data('fooBarBaz') );
//outputs "fizz-buzz" as hyphens are automatically camelCase'd
.data( key, value )
keyA string naming the piece of data to set.
valueThe new data value; it can be any Javascript type including Array or Object.

.attr( attributeName, value )
attributeNameThe name of the attribute to set.
valueA value to set for the attribute.(string)