Javascript 如何使此jQuery内部事件回调在默认情况下引用jQuery对象
因此,默认情况下,jQuery使用HTMLDOM元素作为事件回调中的调用对象Javascript 如何使此jQuery内部事件回调在默认情况下引用jQuery对象,javascript,jquery,function,scope,this,Javascript,Jquery,Function,Scope,This,因此,默认情况下,jQuery使用HTMLDOM元素作为事件回调中的调用对象 var el = $("#foo"); el.on("click", function() { // this will output a div element console.log(this); }); 有没有一种简单的方法可以让它在默认情况下使用jQuery对象作为调用函数 所以“this”引用jQuery对象,我不必将“this”包装在jQuery构
var el = $("#foo");
el.on("click", function()
{
// this will output a div element
console.log(this);
});
有没有一种简单的方法可以让它在默认情况下使用jQuery对象作为调用函数
所以“this”引用jQuery对象,我不必将“this”包装在jQuery构造函数中
$("#foo").on("click", function()
{
// this will instead output the jQuery object el declared above
console.log(this);
this.addClass("fee").find(".roo").remove();
});
我希望避免创建变量名,只使用“this”来引用添加了侦听器的jQuery对象。您可以创建自己的处理程序,该处理程序调用绑定到jQuery集合的函数:
constonclick=(选择器,回调)=>{
const jQueryCollection=$(选择器);
jQueryCollection.on('click',callback.bind(jQueryCollection));
};
onClick(#foo),function(){
this.addClass(“fee”).find(“.roo”).remove();
});代码>
。费用{
背景颜色:黄色;
}
福
如果可能的话,我想使用一个预先存在的选项,但因为似乎没有
我改为在
函数上重写了
这主要归功于CertainPerformance,但此解决方案效果最好,因为它覆盖了回调,并使用了on
上可以使用的4个可用参数
(function ($)
{
let originalOn = $.fn.on;
$.fn.on = function(...args)
{
for(let key in args)
{
if(typeof(args[key]) == "function")
{
let originalCallback = args[key];
args[key] = function(...args)
{
originalCallback.bind($(this))(...args);
}
}
}
originalOn.bind(this)(...args);
}
})($);