Javascript Backbone.js - 事件,知道点击了什么
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5680807/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
backbone.js - events, knowing what was clicked
提问by Matthew
In one of my backbone.js view classes, I have something like:
在我的一个backbone.js 视图类中,我有类似的东西:
...
events: {
'click ul#perpage span' : 'perpage'
},
perpage: function() {
// Access the text of the span that was clicked here
// Something like: alert($(element).text())
},
...
because my per page markup might have something like:
因为我的每页标记可能有以下内容:
<ul id="perpage">
<li><span>5</span></li>
<li><span>10</span></li>
</ul>
So how exactly can I find information about the element that caused the event? Or in this instance, that was clicked?
那么我究竟如何才能找到有关导致事件的元素的信息呢?或者在这种情况下,它被点击了?
回答by Jamie Wong
Normally on an event bind, you would just use $(this)
, but I'm fairly sure Backbone views are set up so that this
always refer to the view, so try this:
通常在事件绑定中,您只需使用$(this)
,但我相当确定 Backbone 视图已设置,以便this
始终引用该视图,因此请尝试以下操作:
perpage: function(ev) {
alert($(ev.target).text());
}
REALLY LATE EDIT: You probably want to use $(ev.currentTarget)
. See dicussion on pawlik's answer below
真的很晚编辑:您可能想要使用$(ev.currentTarget)
. 请参阅下面关于 pawlik 回答的讨论
回答by pawlik
ev.target
can be misleading, you should use ev.currentTarget
as described on http://www.quirksmode.org/js/events_order.html
ev.target
可能会产生误导,您应该ev.currentTarget
按照http://www.quirksmode.org/js/events_order.html 中的描述使用
回答by Nvan
You can get any attribute you want. ev
works as this
:
你可以得到任何你想要的属性。ev
工作原理this
:
perpage: function(ev) {
console.log($(ev.target).attr('name'));
}