Javascript不适用于ajax生成的代码?

tho*_*lin 3 javascript ajax iframe jquery file-upload

我正在使用jQuery表单插件上传文件.该插件使用隐藏的iframe

上传而不刷新页面.一切正常,除了javascript无法正常工作

生成的代码.这是我的代码:

    <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>
Run Code Online (Sandbox Code Playgroud)

此表单将图像上载到服务器,服务器将返回一些处理过的图像.

<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>
Run Code Online (Sandbox Code Playgroud)

responseText包含一些图像.

  <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>
Run Code Online (Sandbox Code Playgroud)

我写了这些代码来测试:

$('.choose_avatar').click(function() { /* Just for test */
    alert('hello');
});
Run Code Online (Sandbox Code Playgroud)

奇怪的是,click函数对这些生成的代码不起作用.有人可以帮帮我吗?谢谢.

ale*_*lex 9

您必须live()手动使用或手动将click处理程序放在常量的父元素上,并检查event.target是否单击了哪一个.

live无论如何,这是如何在引擎盖下工作,所以只要坚持下去:)

请注意,如果您使用的是较新的jQuery,请使用on()而不是live().