你好JS:[6]target?

Tags: 事件, 物件,

事件中event的 target 和 currentTarget 以及 this 的區別,往往令許多初學者分清,其實三者的區別沒有那麼難,之所以理解不了,恐怕和書本上那些抽象的理念有關。

你好JS:[6]target 、currentTarget 、this

工具/原料

JS

javaScript

javaScript事件

簡單說一下區別

用最簡單的語言總結:

target: 代表當前目標物件(事件作用的物件)

currentTarget: 代表註冊監聽器的物件

this: 和currentTarget一樣,即它們的作用相等。

ps:什麼是“事件作用的物件”?什麼是註冊監聽器的物件?

>事件作用的物件: 如果是一個點選事件的話,那麼你點選了誰,誰就是這個點選事件的作用物件

你打了誰,誰就是被你打了的物件

>註冊監聽器的物件: 監聽事件的物件(元素)你點選的元素不一定就註冊了監聽器,也許是它的子元素或者父元素。

總結:判斷三者的關鍵是:弄清到底是誰註冊了監聽器,又是誰被點選了(對事件產生作用了)。

currentTarge、this是和“註冊監聽器的物件”是一夥的。target和“當前目標物件”在一個門派的。

例子

例子1:

你好JS:[6]target 、currentTarget 、this

你好JS:[6]target 、currentTarget 、this

執行程式碼,點選T元素,結果:true true

你好JS:[6]target 、currentTarget 、this

你好JS:[6]target 、currentTarget 、this

結論:

事件作用的元素(物件) = 註冊監聽器的元素(物件)

event.currentTarget = this = event.target = 事件作用的元素(物件) --(例子中的T)

你好JS:[6]target 、currentTarget 、this

例子2:

你好JS:[6]target 、currentTarget 、this

執行程式碼,點選T元素:

你好JS:[6]target 、currentTarget 、this

結果是:

1:true

2:false

3:true

你好JS:[6]target 、currentTarget 、this

你好JS:[6]target 、currentTarget 、this

你好JS:[6]target 、currentTarget 、this

分析:

div T 雖然沒有註冊監聽器,可是當點選它的時候,點選事件會冒泡,當冒泡到body元素時,body的監聽器就會處理這個點選事件。

執行程式碼,點選body元素:

你好JS:[6]target 、currentTarget 、this

結果是:

1:true

2:true

3:true

你好JS:[6]target 、currentTarget 、this

你好JS:[6]target 、currentTarget 、this

你好JS:[6]target 、currentTarget 、this

分析:

body是T的父元素,因此點選body根本不會冒泡到T,除非遇到的是捕獲事件(onclick是冒泡事件)

結論:

事件作用的元素(物件) =! 註冊監聽器的元素(物件) ("=!"表示不等於)

event.currentTarget = this = 註冊監聽器的元素(物件) --(例子中的document.body)

event.target = 事件作用的元素(物件) --(例子中的T)

你好JS:[6]target 、currentTarget 、this

注意事項

本經驗由本人原創,沒有功勞也有苦勞,沒有苦勞也有疲勞,希望能投個票鼓勵一下!

相關問題答案