jQuery $(this) 在 Nodejs 模块上“未定义”(使用 Browserify)

aca*_*ana 3 javascript jquery node.js browserify ecmascript-6

我创建了以下NodeJs模块:

import $ from 'jquery';

module.exports = () => {

  $("#clients-table tbody tr").click(() => {

    let $this = $(this);

    console.log($this);
    console.log($(this));
    console.log($(this).attr("class"));
    console.log($("#clients-table tbody tr").attr("class"));
    console.log("end");
  });
}
Run Code Online (Sandbox Code Playgroud)

我的Browserify入口点如下所示:

"use strict";

import $ from 'jquery';
import test from './test';

test();
Run Code Online (Sandbox Code Playgroud)

当我点击元素时,点击事件被触发,但是$(this)undefined. 这是不同的结果console.logs

test.js:9 he.fn.init {}
test.js:10 he.fn.init {}
test.js:11 undefined
test.js:12 test
test.js:13 end
Run Code Online (Sandbox Code Playgroud)

知道为什么吗?

kuk*_*kuz 6

Arrow functions不要绑定它自己的this参数 - 这就是你得到的原因undefined- 所以你可以使用普通函数模式:

$("#clients-table tbody tr").click(function() {

    let $this = $(this);

    console.log($this);
    console.log($(this));
    console.log($(this).attr("class"));
    console.log($("#clients-table tbody tr").attr("class"));
    console.log("end");
  });
Run Code Online (Sandbox Code Playgroud)