Difference between revisions of "AJAX&Jquery"

From Hawk Wiki
Jump to: navigation, search
(Created page with "==JavaScript== Closure. <pre> <script> function say667() { // Local variable that ends up within closure var num = 666; //var sayAlert = function() { alert(num); } re...")
 
(Jquery Data & Attribute)
Line 18: Line 18:
 
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==
 +
</pre>
 
<a id="foo" data-foo="bar" href="#">foo!</a>
 
<a id="foo" data-foo="bar" href="#">foo!</a>
 
The data can then be accessed using .data() in jQuery:
 
The data can then be accessed using .data() in jQuery:
Line 30: Line 31:
  
 
console.log( $('#foo').attr('data-foo') );
 
console.log( $('#foo').attr('data-foo') );
//outputs "bar" as the <b>attribute was never changed</b>
+
//outputs "bar" as the attribute was never changed
  
 
console.log( $('#foo').data('foo') );
 
console.log( $('#foo').data('foo') );
Line 39: Line 40:
 
console.log( $('#bar').data('fooBarBaz') );
 
console.log( $('#bar').data('fooBarBaz') );
 
//outputs "fizz-buzz" as hyphens are automatically camelCase'd
 
//outputs "fizz-buzz" as hyphens are automatically camelCase'd
 +
</pre>

Revision as of 02:46, 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

</pre> <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 </pre>