[英]Dynamic Items and jQuery Event Binding
I am currently populating a list dynamically based on some web calls. 我目前正在根据一些网络电话动态填充列表。 When these calls return I use an HTML template to add another item to the list based on the call response.
这些呼叫返回时,我将使用HTML模板根据呼叫响应将另一个项目添加到列表中。 I also am trying to attach some events to these objects using jQuery, but when I generate the items it seems like only the last item generated has the appropriate events firing.
我还尝试使用jQuery将一些事件附加到这些对象,但是当我生成项目时,似乎只有最后生成的项目才触发适当的事件。
So here is the code: 所以这是代码:
The javascript generates the html string and the adds it to the list: javascript生成html字符串并将其添加到列表中:
List.innerHTML += html;
The html is generated using moustache.js and renders properly, I set the id in the template before adding it. 该html使用moustache.js生成并正确呈现,我在添加模板之前在模板中设置了id。
The template has this form: 模板具有以下形式:
var template = '<li style="width:400px; height:100px" id="{{id}}" ><img src="{{source}}" style="float:left"/>{{title}} <button id="{{id}}button">Delete</button></li>';
Where all the elements are replaced appropriately. 适当替换所有元素的位置。
Then I try to attach a click event to the button and a double click event to the entire list object: 然后,我尝试将click事件附加到按钮,并将doubleclick事件附加到整个列表对象:
$('#' +id +'button').bind('click', function() {
//SOME STUFF GOES HERE
});
$('#' +id +'button').bind('dblclick', function() {
//MORE STUFF GOES HERE
});
Im not sure why the event wouldnt attach to each object, am I missing something? 我不确定为什么事件不会附加到每个对象上,我是否错过了某些东西?
Thanks! 谢谢!
The DOM might not have been updated on the browser by the time you add the click handlers. 添加点击处理程序时,DOM可能尚未在浏览器上更新。 You have a couple options:
您有两种选择:
Example 1: 范例1:
$('body').on('click', '#' +id +'button', function () { /* foo */ });
Example 2: 范例2:
$('#' +id +'button', myHtml).on('click', function () { /* foo */ });
List.append(myHtml);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.