2008年8月14日 星期四

Working with Events, part 1

http://www.learningjquery.com/2008/03/working-with-events-part-1
http://manalang.com/jquery/docs/index.html#insertAfter-expr
http://manalang.com/jquery/docs/index.html#parents
http://www.quirksmode.org/js/events_order.html

Event Delegation. With event delegation, we bind the event handler to a containing element that remains in the DOM and then check for the target of the event.

$(document).ready(function() {
$('#list1 li.special button').click(function() {
var $newLi = $('<li class="special">special and new <button>I am new</button></li>');
$(this).parent().after($newLi);
});
});

$(document).ready(function() {
$('#list2').click(function(event) {
var $newLi = $('<li class="special">special and new <button>I am new</button></li>');
var $tgt = $(event.target);
if ($tgt.is('button'))
$tgt.parent().after($newLi);
}

// next 2 lines show that you've clicked on the ul
var bgc = $(this).css('backgroundColor');
$(this).css({backgroundColor: bgc == '#ffcccc' || bgc == 'rgb(255, 204, 204)' ? '#ccccff' : '#ffcccc'});
});
});

parent(), after(), $(evnet.target), $(this), css()

可以用evnet.target 來取得被trigger的target, $(this)是整個$('#list2')

沒有留言: