$(this) 正在选择窗口对象而不是单击元素 jquery [英] $(this) is selecting window object instead of clicked element jquery

查看:30
本文介绍了$(this) 正在选择窗口对象而不是单击元素 jquery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常奇怪的问题.我只想选择一个点击的元素.我做了很多次,它总是有效,但是这一次,jQuery $(this) 选择器没有选择被点击的元素,它选择了窗口对象.如果您有任何想法,请告诉我,这可能是什么原因.我正在使用 jQuery 2.1.4 和 Twitter Bootstrap 3.3.5

I have a really strange issue. I simply want to select a clicked element. I did this a lot of times and it always worked but this time, the jQuery $(this) selector doesn't select the clicked element, it selects the window object. Please let me know, if you have an idea, what could be the reason for this. I am using jQuery 2.1.4 and Twitters Bootstrap 3.3.5

HTML:

<a class="btn btn-danger btn-xs delete-file"><i class="fa fa-trash" aria-hidden="true"></i> Löschen</a>

jQuery:

$(document).ready( () => {
   $('.delete-file').on('click', () => {
      let element = $(this);
      console.log(element);
    });
});

控制台输出:

n.fn.init [Window]

代替:

n.fn.init [a.btn.btn-danger.btn-xs.delete-file]

先谢谢你!

推荐答案

这是因为您使用了箭头函数.根据标准函数定义,此函数的内容范围不会改变.要使 this 工作,您需要更改逻辑:

It's because you're using an arrow function. The scope of the contents of this function do not change as per a standard function definition. For this to work you'll need to change the logic:

$(document).ready(() => {
  $('.delete-file').on('click', function() {
    let element = $(this);
    console.log(element);
  });
});

或者,您可以保留箭头函数并通过引发事件的 target 属性检索对被点击元素的引用:

Alternatively you could keep the arrow function and retrieve a reference to the clicked element through the target property of the event that's raised:

$(document).ready( () => {
  $('.delete-file').on('click', e => {
    let element = $(e.target);
    console.log(element);
  });
});

这篇关于$(this) 正在选择窗口对象而不是单击元素 jquery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆