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); // ... });