Difference between revisions of "AJAX&Jquery"

From Hawk Wiki
Jump to: navigation, search
(Jquery Data & Attribute)
(JavaScript)
Line 1: Line 1:
 
==JavaScript==
 
==JavaScript==
 
Closure.  
 
Closure.  
<pre>
+
<pre class="javascript">
 
<script>
 
<script>
 
function say667() {
 
function say667() {
Line 17: Line 17:
 
</pre>
 
</pre>
 
The example will keep var num in the memory. alert 667 and 668 on each call;
 
The example will keep var num in the memory. alert 667 and 668 on each call;
 +
 
==Jquery Data & Attribute==
 
==Jquery Data & Attribute==
 
Attribute does not change when using .data
 
Attribute does not change when using .data

Revision as of 23:19, 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)