我添加了一个简单的功能:
$.postAndVerify = function(url)
{
// this.event. ?
}
$('#myButton').click(function() {
$.postAndVerify('/url');
});
在其中,我如何知道调用者对象,即#myButton?我当然知道它可以直接通过:
$.postAndVerify = function(url, $triggeredBy)
{
}
$('#myButton').click(function() {
$.postAndVerify('/url', $(this));
});
但是这会产生大量的样板代码。
最佳答案
您可以通过将方法分配给 $.fn
而不是 $
来使其成为插件方法
$.fn.postAndVerify = function(url){
console.log(this)// jQuery object
}
$('#myButton').click(function() {
$(this).postAndVerify('/url' );
});
或者您可以使用Function#bind()
关于javascript - 在添加的 jQuery 函数中,我可以知道触发的 DOM 对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53351498/