2008年5月3日 星期六

jQuery memo 3


$(document).ready(function(){
if (this.id == 'switcher-narrow') {
$('body').addClass('narrow');
}
else if (this.id == 'switcher-large') {
$('body').addClass('large');
}
});


Compound Event
ready(), toggle(), hover()

toggle
$(document).ready(function() {
$('#switcher h3').toggle(function() {
$('#switcher .button').addClass('hidden');
}, function() {
$('#switcher .button').removeClass('hidden');
});
});

$(document).ready(function() {
$('#switcher h3').click(function() {
$('#switcher .button').toggleClass('hidden');
});
});


hover
$(document).ready(function() {
$('#switcher .button').hover(function() {
$(this).addClass('hover');
}, function() {
$(this).removeClass('hover');
});
});



The Journey of Event
event capturing
event bubbling



Preventing Event Bubbling

$(document).ready(function() {
$('#switcher').click(function(event) {
if (event.target == this) {
$('#switcher .button').toggleClass('hidden');
}
});
});

event.target 可以知道第一個觸發 event 的是哪個element

Stopping Event Propagation
event.stopPropagation()



Default Actions
.preventDefault() 阻止一些例如link 的預設行為

.preventDefault + .stopPropagation = return false



Removing an Event Handler

$(document).ready(function() {
var toggleStyleSwitcher = function() {
$('#switcher .button').toggleClass('hidden');
};

$('#switcher').click(toggleStyleSwitcher);

$('#switcher-narrow, #switcher-large').click(function() {
$('#switcher').unbind('click', toggleStyleSwitcher);
});
});

只執行一次toggle
$(document).ready(function() {
$('#switcher').one('click', toggleStyleSwitcher);
})



Simulating User Interaction
幫妳觸發 click

$(document).ready(function() {
$('#switcher').trigger('click');
});

$(document).ready(function() {
$('#switcher').click();
});

沒有留言: