# 5.3 事件觸發寫法及注意事項

## click 事件與事件冒泡狀況(Event Bubbling)

click 事件的寫法，使用 **`.on()`**：

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

範例：

{% embed url="<https://codepen.io/carlos411/pen/YzyzbMW>" %}

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

```javascript
e.stopPropagation();
```

### 介面：燈箱

{% embed url="<https://codepen.io/carlos411/pen/xxWMeNd>" %}

## 滑鼠相關事件

留意事件冒泡狀況。

### mouseenter、mouseleave

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

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

範例：

{% embed url="<https://codepen.io/carlos411/pen/vYNYwVG>" %}

### mouseover、mouseout

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

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

範例(不用背，要會觀察)：

{% embed url="<https://codepen.io/carlos411/pen/zYvYQyX>" %}

### mousemove

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

範例：

{% embed url="<https://codepen.io/carlos411/pen/RwWwzaV>" %}

## 關於 this

以下寫法為例，事件觸發時，this 指的就是那個元素。

```javascript
$("#the_link").on("click", function(e){
  this.href = "https://tw.yahoo.com";
});
```

所以可把 this 丟到 jQuery 函式中，使用 jQuery 提供的函式：

```javascript
$("#the_link").on("click", function(e){
  $(this).attr("href", "https://tw.yahoo.com");
});
```

範例：

{% embed url="<https://codepen.io/carlos411/pen/abvbgRm>" %}

## 停止連結的預設行為

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

```javascript
e.preventDefault();
```

範例：

{% embed url="<https://codepen.io/carlos411/pen/ZEbEdKg>" %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.webmix.cc/jquery/5.-shi-jian-jian-ting-event-handling/5.4-ji-ben-de-shi-jian.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
