javascript 如何在主干中动态生成的按钮上绑定事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6987386/
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
How to bind events on dynamic generated buttons in backbone?
提问by JABD
How do I bind click event on dynamic generated buttons in backbone.js?
如何在backbone.js 中动态生成的按钮上绑定click 事件?
window.PackageView = Backbone.View.extend({
tagName: "div",
className: "package-template",
events:{
'click #display-nodes' : 'main', // This button is declared in my HTML code and calls main method successfully.
'click .display' : 'disp', // This is dynamic button generated with class as display
},
getAction: function(nodeId){ // Get Actions from NodeId and generate buttons
$('.nodes').append("<button>" + action.Name + "</button>"); //Generate Buttons
$(".nodes button").addClass("display");
},
disp: function(){
alert("Inside Disp Function");
},
On clicking #display-nodes
the nodes are displayed as required but .display
is not working. How do I make this button call the function?
单击时#display-nodes
,节点会根据需要显示但.display
不起作用。如何让这个按钮调用函数?
回答by Benjamin Atkin
A Backbone view can receive events from dynamically generated DOM elements, through the events
property, as long as the dynamically generated DOM elements are descendants of the view's el
. The relevant code is in delegateEvents(). It uses jQuery's delegate()selector method.
一个骨干视图可以接收来自动态生成的DOM元素的事件,通过events
属性,只要动态地生成的DOM元素有视图的后裔el
。相关代码在delegateEvents() 中。它使用 jQuery 的delegate()选择器方法。
The most likely reason it's not working for you is that the newly created <button>
is not a descendant of the view's el
. Am I right?
它对您不起作用的最可能原因是新创建<button>
的不是视图的el
. 我对吗?
If this is the case and you want to keep the element outside of the view's el
, you can remove it from your view's events
property and delegate on another element in your view's init
method.
如果是这种情况,并且您希望将元素保留在视图的 之外,则el
可以将其从视图的events
属性中删除,并委托给视图init
方法中的另一个元素。