William Jiang

JavaScript,PHP,Node,Perl,LAMP Web Developer – http://williamjxj.com; https://github.com/williamjxj?tab=repositories

jQuery examples summary 1

While frequently access live examples from http://api.jquery.com/, I find some examples are very useful. Here is my collection and summary from http://api.jquery.com/ for quick retrieve and reference:

jQuery Events

//1. click
$('selector').click(function(event) {
 event.preventDefault();
 $op = $(event.target); //which is more precise than $(this);
 …
}
//2. submit
$('selector').bind('submit', function(event) {
 event.preventDeault();
 $op = $(event.target); //which is more precise than $(this);
 …
}
//3. hover
$('selector').hover(function() {  // mouseover
 }, function() { //mouseout
});
//4. change
$('selector').live('change', function() {
 $.post(url, $('#f_'+division).serialize(), function(data) {  //AJAX-style model calling.
  $('#f_'+division).parent().parent().find('td:last label').text(data); //refresh
 });
}

jQuery DOM Position

//1. append()
$('.inner').append('<p>Test</p>');
$('.container').append($('h2'));
$("p").append("<strong>Hello</strong>");
$("p").append( $("strong") );
$("#something").hide().append(data).fadeIn('slow');

//2. appendTo( target )
$('<p>Test</p>').appendTo('.inner');
$('h2').appendTo($('.container'));
$("span").appendTo("#foo"); 
jQuery('#lista').live('dblclick', function() {
  $('#lista option:selected').appendTo('#listb');
});
$('<option>').val('newValue').text('Second Option')
 .appendTo('select[name=uniqueName]');
$("<div>inner</div>")
 .appendTo($("<div>outer</div>")
 .appendTo("body"));

//3. prepend()
$('.inner').prepend('<p>Test</p>');
$('.container').prepend($('h2'));
$("p").prepend(document.createTextNode("Hello "));
$("p").prepend( $("b") );

var $newdiv1 = $('<div id="object1"/>'),
newdiv2 = document.createElement('div'),
existingdiv1 = document.getElementById('foo');
$('body').prepend($newdiv1, [newdiv2, existingdiv1]);

//4. prependTo( target )
$('<p>Test</p>').prependTo('.inner');
$('h2').prependTo($('.container'));
$("span").prependTo("#foo"); 
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: