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

我创build了以下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"); }); } 

我的Browserify入口点如下所示:

 "use strict"; import $ from 'jquery'; import test from './test'; test(); 

当我点击元素时,点击事件被触发,但$(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 

任何想法为什么?

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"); }); 

另一个答案可能是更现实的一个,但要注意,你也可以停止使用this和做

 $("#clients-table tbody tr").click(evt => { let $this = $(evt.currentTarget); // ... }); 
    Interesting Posts