I’m using jQuery form plugin to upload files. The plugin uses a hidden iframe to
upload without refreshing the page. Everything works fine except javascript doesn’t work on
generated code. Here’s my code:
<form id="image_form" action="" method="post" enctype="multipart/form-data">
<input type="file" id="image_file" name="image_file"><br>
<input type="submit" value="upload">
</form>
<div id="avatar_wrapper">
</div>
This form uploads an image to server and server will return some processed images.
<script type="text/javascript">
$(document).ready(function() {
var options = {
success: showResponse,
dataType: 'html'
};
$('#image_form').ajaxForm(options);
$('.choose_avatar').hover(function() { /* Just for test */
alert('hello');
});
});
function showResponse(responseText, statusText, xhr, $form) {
$('#avatar_wrapper').append(responseText);
}
</script>
responseText contains some images.
<img src="http://localhost/avatar/0.jpg" class="choose_avatar" choice=0>
<img src="http://localhost/avatar/1.jpg" class="choose_avatar" choice=1>
<img src="http://localhost/avatar/2.jpg" class="choose_avatar" choice=2>
I wrote these code to test:
$('.choose_avatar').click(function() { /* Just for test */
alert('hello');
});
It’s strange that click function doesn’t work on these generated code.
Can someone please help me with this?Thanks.
You will have to use
live(), or do it manually, place aclickhandler on the parent element that is constant, and checkevent.targetto see which one was clicked.This is how
liveworks under the hood, anyway, so just stick with it 🙂Note that if you’re using a newer jQuery, then use
on()instead oflive().