开发者

Javascript doesn't work on ajax generated code?

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/avata开发者_运维技巧r/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 a click handler on the parent element that is constant, and check event.target to see which one was clicked.

This is how live works under the hood, anyway, so just stick with it :)

Note that if you're using a newer jQuery, then use on() instead of live().


You will have to use .live on these dynamically generated elements.

$('.choose_avatar').live("click", function() { /* Just for test */
    alert('hello');
});


On the container avatar_wrapper you must bind a live/delegate listener :

$('#avatar_wrapper').delegate('.choose_avatar','click',function() {
    alert('hello');
});

Hope it helps!


When you do a $('.choose_avatar'), you are selecting elements with class choose_avatar (which don't exist yet) and attaching the event handler. Which obviously won't work if the elements are loaded dynamically. A more correct approach is to handle the delegated event on the wrapper div like so,

$('#avatar_wrapper').delegate('img.choose_avatar', 'click', function (e) {
    // do stuff
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜