5.3 事件觸發寫法及注意事項
click 事件與事件冒泡狀況(Event Bubbling)
click 事件的寫法,使用 .on()
:
$("div.outer_block").on("click", function(){
// 點擊後,要執行的程式...
});
範例:
如果要停止事件冒泡狀況發生,在正確的位置執行以下程式:
e.stopPropagation();
介面:燈箱
註:練習寫蓋住畫面的 CSS,請建立 lightbox.html
網頁檔。
滑鼠相關事件
留意事件冒泡狀況。
mouseenter、mouseleave
mouseenter:滑鼠移入時觸發。(不會發生冒泡狀況)
mouseleave:滑鼠移出時觸發。(不會發生冒泡狀況)
範例:
mouseover、mouseout
mouseover:滑鼠移入時觸發。(會發生冒泡狀況)
mouseout:滑鼠移出時觸發。(會發生冒泡狀況)
範例(不用背,要會觀察):
mousemove
說明:滑鼠游標在元素上移動時觸發。(會發生事件冒泡狀況)
範例:
關於 this
以下寫法為例,事件觸發時,this 指的就是那個元素。
$("#the_link").on("click", function(e){
this.href = "https://tw.yahoo.com";
});
所以可把 this 丟到 jQuery 函式中,使用 jQuery 提供的函式:
$("#the_link").on("click", function(e){
$(this).attr("href", "https://tw.yahoo.com");
});
範例:
停止連結的預設行為
連結的預設行為是是將連結開啟。可以透過以下程式來停止:
e.preventDefault();
範例:
Last updated