onClick没有处理ajax生成的内容

时间:2014-03-11 16:36:01

标签: javascript php jquery ajax

我的代码没有显示错误,但也没有按预期工作。来自ajax调用的输出工作正常,但我无法从onClick中获取任何内容,没有错误消息,没有。

HTML

<div id="serials"></div>
<div id="accounts_info_key" style="text-align:left"></div>

Ajax调用

$(document).ready(function() { 
$('.tab2').click(function(){
        var account_id = $('#account_id').val();
              $.ajax({
                 url: 'ajax/account_info_serials_ajax.php',
                 type:'POST',
                 dataType: 'json',
                 data: 'account_id='+account_id,
                        success: function(response){
                $('#serials').html(response.table),
                $('#accounts_info_key').html(response.key),
                $('.drop_down').hide();
                },
              error:function (xhr, ajaxOptions, thrownError){
              alert(thrownError);
               } // End of success function of ajax form
              }); //end of ajax
       });//close trigger
  });//close whole function

PHP

   $response = '';
   $response .='<div class="question">';
   $response .='plop';

   $response .='</div>';
   $response .='<div class="drop_down">';
   $response .='bob';
   $response .='</div>';

   $output_array = array(
              'table' => $response,
              'key' => $key,
              'count' => $count 
    );

  echo json_encode($output_array);

jquery onclick

$(document).ready(function() {  
    $('#serials').on("click", ".question", function(e){
        alert('smeg');  
    });
});

请注意,我不是问怎么做,我问为什么我的版本不起作用,这不是一个重复的问题

2 个答案:

答案 0 :(得分:3)

我创造了一个小提琴,展示了我应该如何做到http://jsfiddle.net/6VtA8/

$(document).ready(function () {
    $('.tab2').click(function () {
        var account_id = $('#account_id').val();
        $.ajax({
            url: '/echo/json/',
            type: 'POST',
            dataType: 'json',
            data: {'something':'else'}
        }).done( function (response) { $('#serials').html('<div class="question ">abcd</div>'); });
    });
}); //close whole function 

$(document).ready(function () {
    $('#serials').on("click", ".question", function (e) {
        alert('smeg');
    });
});

有多种原因导致您的代码无效。甚至可能是你的div(来自某些css规则)最终的高度为0,因此事件不会触发。因此,我选择做一些重写而不是调试。

答案 1 :(得分:0)

你必须订阅活动点击#serials一旦它在dom中。所以当你的ajax回调结束并且.question在dom中时,你订阅#serials上的点击。

相关问题