5.4 事件觸發寫法及注意事項

click 事件與事件冒泡狀況(Event Bubble Up)

click 事件的寫法,使用 .on()

$("div.outer_block").on("click", function(){
  
  // 點擊後,要執行的程式...
  
});

範例:

如果要停止事件冒泡狀況發生,在正確的位置執行以下程式:

e.stopPropagation();

範例:燈箱(或稱做 modal)

滑鼠相關事件:注意事件冒泡狀況

mouseenter、mouseleave

mouseenter:滑鼠移入時觸發。(不會發生冒泡狀況)

mouseleave:滑鼠移出時觸發。(不會發生冒泡狀況)

範例:

mouseover、mouseout

mouseover:滑鼠移入時觸發。(會發生冒泡狀況)

mouseout:滑鼠移出時觸發。(會發生冒泡狀況)

範例(不用背,要會觀察):

mousemove

說明:滑鼠游標在元素上移動時觸發。(會發生事件冒泡狀況)

範例:5_4_mousemove.html

關於 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");
});

範例: 5_4_this.html

停止預設行為

連結

連結的預設行為是是將連結開啟。可以透過以下程式來停止:

e.preventDefault();

範例:5_4_link_prevent_default.html

練習

  • 停止「表單資料送出的預設行為」。

  • 停止「文字出現在欄位上的預設行為」。

建立 jquery/practice/form_submit.html 檔案,內容如下:

<!doctype html>
<html lang="zh-Hant">
  <head>
    <meta charset="utf-8">
    <title>jQuery 相關練習</title>
  </head>
  <body>

    <form action="https://tw.yahoo.com" method="get" id="myform">
      <input type="text" id="myname" name="myname">
      <button type="submit">資料送出</button>
    </form>

    <script src="./vendors/jquery/jquery-3.4.1.min.js"></script>
    <script>
      $(function(){
        // code here...
      });
    </script>
  </body>
</html>

說明:表單送出事件的寫法:

$("#myform").on("submit", function(){
});

接著請撰寫以下兩個:

  • 如果沒有填寫資料,表單不能送出,然後用 alert() 顯示「請輸入資料」。

  • 如果有填寫資料,就表單按鈕原來預設的形式將資料送出。

參考作法:

Last updated