在研究JQuery'on'方法时,我遇到了一个有趣的问题。我尝试了很多,但从未有任何具体的方法来实现它
我想要的是?
我有一个HTML以下(我不能编辑任何内容)
<div id='apple1' class="apple"> Apple1 </div>
<div id='apple2' class="apple"> Apple2 </div>
<div id='apple3' class="apple"> Apple3 </div>
首先让我们看一个函数,我们将在单击回调中使用它
var fun = function(event) {
console.log('example', this);
}
现在让我们将它附加到HTML元素
$('.apple').on('click', fun)
现在点击Apple1后我们将在控制台中获取此信息
example, <div class=".apple" id="apple1">
看到片段:
var fun = function(event) {
console.log('example', this);
}
$('.apple').on('click', fun)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='apple1' class="apple"> Apple1 </div>
<div id='apple2' class="apple"> Apple2 </div>
<div id='apple3' class="apple"> Apple3 </div>
现在我想将回调函数绑定到其他东西,所以让我们将上面的代码更改为:
var funBinded = fun.bind({name: 'JQuery'})
$('.apple').on('click', funBinded)
输出将是:
example, >{name: 'JQuery'}
看到片段:
var fun = function(event) {
console.log('example', this);
}
var funBinded = fun.bind({name: 'JQuery'})
$('.apple').on('click', funBinded)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='apple1' class="apple"> Apple1 </div>
<div id='apple2' class="apple"> Apple2 </div>
<div id='apple3' class="apple"> Apple3 </div>
现在这里'this'将指向绑定对象,而不是单击HTML元素。在第二种情况下,任何一个div('Apple1','Apple2','Apple3')都可以触发点击。
那么我怎么知道点击了哪个元素?
另请注意:我无法对HTML文档进行任何更改,因此我无法使用以下方法:
<div id='apple1' class="apple" onclick="fun(event, this)"> Apple1 </div>
我也不想使用even.target因为它可以让我点击最里面的元素而不是注册事件的那个元素
当您更改了处理程序函数的范围(通过使用bind()
)时,this
将不再是被单击的元素。
如果仍然需要获取对事件绑定的元素的引用(不是引发事件的元素,正如您的问题所提到的那样),请使用currentTarget
的event
属性,该属性作为参数传递给事件处理程序:
var fun = function(e) {
console.log('example', this);
console.log(e.currentTarget);
}
var funBinded = fun.bind({
name: 'JQuery'
})
$('.apple').on('click', funBinded)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="apple1" class="apple"><span>Apple1</span></div>
<div id="apple2" class="apple"><span>Apple2</span></div>
<div id="apple3" class="apple"><span>Apple3</span></div>
请注意,我将文本包装在.apple
中的span
元素中,以显示currentTarget
属性返回正确的元素。