使用.on的jQuery事件委托(此参考) [英] jQuery event delegation with .on (this reference)
问题描述
在委托的.on事件中此引用在哪里? 示例:
Where does this reference to in a delegated .on event? Example:
$('#foo').on('click', $('.bar'), function() {
console.log(this);
});
在示例中,这将引用#foo.但是我如何访问被单击的条形元素?我可能有5个条形元素,我想知道单击了哪一个.
In the example this will reference to #foo. But how do i access the bar element that got clicked? I might have 5 bar elements and I want to know which one was clicked.
谢谢
抱歉,我将#bar更改为.bar(因为它存在多次).
Sorry i changed #bar to .bar (since it exists multiple times).
我应该只使用'.bar'的答案有所帮助.但是,如果我有这样的选择器怎么办:
The answer that i should just use '.bar' helped. But what if i have selector like this:
$('.bar').find('a');
我该如何合并这样的东西?
How would i incorporate something like this?
这行不通:(因为这将引用#foo)
This won't work: (cause this will reference to #foo)
$('#foo').on('click', $('.bar').find('a'), function() {
console.log(this);
});
推荐答案
将其更改为此...
$('#foo').on('click', '.bar', function() {
console.log(this);
});
现在this
将成为单击的.bar
.
如果要使用jQuery对象,请照常使用$(this)
.
If you want a jQuery object then use $(this)
as normal.
修改
根据对问题代码的更改,您将需要此...
As per the change to question code, you'll need this...
$('#foo').on('click', '.bar a'), function() {
console.log(this);
});
这只是将click事件处理程序扩展到document.ready中可能不存在的.bar
元素内的链接.
That simply extends the click event handler to links inside .bar
elements that may not exist at document.ready.
这篇关于使用.on的jQuery事件委托(此参考)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!