我总是在jQuery中编写事件处理程序,如下所示:
$('.some-class').click(function() {
alert('bla');
});
我了解到最好避免在回调中使用匿名函数,所以我尝试这样:
var function someMethod = function() {
alert('bla');
};
$('.some-class').click(someMethod);
如何将对我点击的元素的引用传递给someMethod
?
答案 0 :(得分:2)
使用this
:
var someMethod = function() {
console.log(this); // => <button class="some-class">OK</button>
console.log($(this).text()); // => OK
};
$('.some-class').click(someMethod);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="some-class">OK</button>