在添加的jQuery函数中,我可以知道触发的DOM对象吗?

时间:2018-11-17 13:01:29

标签: javascript jquery

我添加了一个简单的功能:

$.postAndVerify = function(url)
{
    // this.event. ?
}

$('#myButton').click(function() {
    $.postAndVerify('/url');
});
在其中的

,我怎么知道调用者对象,即#myButton?我当然知道可以通过:

$.postAndVerify = function(url, $triggeredBy)
{
}

$('#myButton').click(function() {
    $.postAndVerify('/url', $(this));
});

但这会导致大量的样板代码。

2 个答案:

答案 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>

相关问题