我添加了一个简单的功能:
$.postAndVerify = function(url)
{
// this.event. ?
}
$('#myButton').click(function() {
$.postAndVerify('/url');
});
在其中的,我怎么知道调用者对象,即#myButton?我当然知道可以通过:
$.postAndVerify = function(url, $triggeredBy)
{
}
$('#myButton').click(function() {
$.postAndVerify('/url', $(this));
});
但这会导致大量的样板代码。
答案 0 :(得分:2)
您可以通过将方法分配给$.fn
而不是$
来使其成为插件方法
$.fn.postAndVerify = function(url){
console.log(this)// jQuery object
}
$('#myButton').click(function() {
$(this).postAndVerify('/url' );
});
或者您可以使用Function#bind()
答案 1 :(得分:1)
您可以尝试使用call method将按钮元素作为this
传递
$.postAndVerify = function (url) {
console.log('this:');
console.log(this);
};
$('#myButton').click(function () {
$.postAndVerify.call(this, '/url');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="myButton" type="button">Click me</button>