【问题标题】:Bind to jquery function issue绑定到 jquery 函数问题
【发布时间】:2018-01-03 09:29:31
【问题描述】:

我在 EcmaScript 6 类中使用 JQuery,并且我有一个事件函数,它在类的实例化时触发,并且该事件包含需要与 Class 交互的不同 JQuery 事件,所以我使用 .bind() 来实现那,一切正常,除了一个事件由于某种原因用我通过.bind(that)方法传递的“that”覆盖了属于jquery元素“this”的this,这是我的代码(一切都适用于这个事件):

var that = this;
$(document).on('click', '[select-file]' , function(event) {
event.preventDefault();


console.log(this);

}.bind(that));

所以控制台日志给了我父类而不是 jquery 元素 正如预期的那样工作:

            $(document).on('click', '[open-file-dialoge]', function(event) {
                event.preventDefault();
                  $('[file-dialoge]').modal('show');
                  if ($(this).attr('mitiupload') == 'false') {
                    // check if multiple upload is disabled
                    that.multiUpload = false;
                    $(this).removeAttr('multiple');
                  }
                  that.insertFiles();
            }.bind(that));

请帮忙,我不明白这里发生了什么,即使它们之间没有太大区别,也不能按预期工作;(

【问题讨论】:

  • 只使用that作为父范围,让jQuery分配自己的this
  • 不知道第二个怎么可能为$(this)工作
  • 如果您不希望 this 引用类实例而是引用元素,为什么还要使用 bind?!
  • charlietfl,它实际上并不能很好地工作,我的错,我没有注意到它没有给我错误

标签: javascript jquery webpack ecmascript-6 es6-class


【解决方案1】:

Function#bind() 在函数中更改this 的上下文。如果你想要当前元素,你可以使用event.currentTarget

var that = {};
$(document).on('click', 'button', function(event) {
  event.preventDefault();
  var el = event.currentTarget;

  console.log('this=', this);
  console.log('el=', el)

}.bind(that));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="test">Click me</button>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-05
    • 1970-01-01
    • 2018-03-19
    • 1970-01-01
    相关资源
    最近更新 更多