[英]jQuery $(this) is “undefined” on a nodejs module (using Browserify)
我創建了以下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();
當我單擊該元素時,將觸發click事件,但是$(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);
// ...
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.