jquery与箭头函数的联系
用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。

浙公网安备 33010602011771号