使用stopPropagation()方法阻止事件冒泡 $(document).ready( function () { $( ' switcher ' ).click( function (event){ if ( this .id == ' switcher-narrow ' ){ $( ' body ' ).addClass( ' narrow ' ); } else if ( this .id == ' switcher-large ' ){ $( ' body ' ).addClass( ' large ' ); } $( ' switcher .button ' ).romoveClass( ' selected ' ); $( this ).addClass( ' selected ' ); event.stopPropagation(); };) });
使用 event.tatget 屬性 明確事件對象
事件處理程序中的變量 event 保存著事件對象。而 event.tatget 屬性保存著發生事件的目標元素。這個屬性是 DOM API 中規定的,但是沒有被所有瀏覽器實現。 jQuery 對這個事件對象進行了必要的擴展,從而在任何瀏覽器中都能夠使用這個屬性。通過 .target ,可以確定 DOM 中首先接收到事件的元素。而且,我們知道 this 引用的是處理事件的 DOM 元素。
使用 event.tatget 屬性 明確事件對象 阻止事件冒泡的代碼如下:
$(document).ready( function () { $( ' switcher ' ).click( function (event){ if (event.target == this ) { $( ' switcher .button ' ).toggleClass( ' hidden ' ); } };) });