用jquery寫一個按鈕點擊事件很簡單的吧,選中這個點擊的按鈕也很簡單,直接$(this)就可以選中了。
//html
<button class="btn">點擊一下嘛</button>
//js
// 普通函數
$('.btn').click(function(){
alert('我要消失啦')
$(this).hide();
console.log($(this)); //選中了當前選中的jquery元素,也就是btn
})
那用箭頭函數如何才能選中當前點擊的按鈕呢?
$('.btn').click((e)=>{
console.log(this); //Window {parent: Window, opener: null, top: Window, length: 0, frames: Window, …}
console.log($(this)); //init [Window]
})
這樣並不可以的!
我們來參考vue
首先 vue的點擊事件 是用 @click = “clickfun()” 屬性 在html中綁定的,
在點擊的函數中 添加$event 參數就可以
<button @click = “clickfun($event)”>點擊</button>
methods: {
clickfun(e) {
// e.target 是你當前點擊的元素
// e.currentTarget 是你綁定事件的元素
}
},
參考鏈接:https://blog.csdn.net/webfront/java/article/details/80310763
所以:
// 箭頭函數
$('.btn').click((e)=>{
console.log(e.target); //選中了當前選中的那個dom元素,也就是btn
console.log($(e.target)); //選中了當前選中的jquery元素,也就是btn
console.log(e.currentTarget); //選中了當前選中的那個dom元素,也就是btn
console.log($(e.currentTarget)); //選中了當前選中的jquery元素,也就是btn
})
這樣完美解決,一般用e.target。
