JQuery: How to attach event to template objects?
I have a template that generates images and I am binding it to div.
<script id="postTemplate" type="text/html">
<div class="post_1">
<div class="postImage"><img src="${ImageUrl}" alt="Image"></div>
</div>
</script>
Then i bind the data
<script>
$("#postTemplate").tmpl(clientData).appendTo("#imagesArea");
</scrip开发者_开发问答t>
now, what i want is add an event handlers to that i just created. something like
("template img").error(function() {});
Adding handlers to things like click seems to work, but error fires off before I can add the handler it seems.
Not sure what your selector "template img" is referencing since I dont see any template elements.
$(function(){
$('template img').live({
click: function() {
// do something on click
},
error: function() {
// do something on error
}
});
});
http://api.jquery.com/live/
$("template").on("error", "img", function(){});
How about
$("#postTemplate img").click(function() { alert('clicked'); });
must be called after you template has been added. Otherwise you will have to use Live
I'm not sure if i get your problem but i guess you can store a reference to the generated object from template before appending it to the #imagesArea
element, attaching events to that reference should work as:
var myGeneratedContent = $("#postTemplate").tmpl(clientData)
myGeneratedContent.appendTo('#imagesArea');
myGeneratedContent.click(function() { [...] });
try
("template img").bind("error",function() {});
You can use .live(), which binds events even if element is created afterwards
$("#imagesArea img").live('click', function(){
//do stuff here
});
精彩评论