2015-11-05 63 views
1

我有一個公告系統,我將所有公告從數據庫中提取出來,並使用Ajax和PHP將它們顯示在屏幕上。JavaScript未在加載PHP時運行HTML

下面是每個公告加載到頁面的代碼:

echo '<div id="announcements_container">'; 
for ($i = $start; $i <= $end; $i++) { 
    ?> 
     <script> 
      formatAnnouncement("<?php echo $announcements[$i]->id; ", ..., ..., ...); 
     </script> 
    <?php 
} 
echo '</div>'; 

這裏是我的功能,接收到的數據發送到PHP和回來格式化的公告。

function formatAnnouncement(id, subject, body, urgent, attachment1, attachment2, poster, time_posted) { 
    $.ajax({ 
     type: "POST", 
     url: "<?php echo base_url().'application/views/user/announcement_block.php'; ?>", 
     data: {id : id, subject : subject, body : body, urgent : urgent, attachment1 : attachment1, attachment2 : attachment2, poster : poster, time_posted : time_posted}, 
     success: function(response) { 
      $("#announcements_container").prepend(response); 
     } 
    }); 
} 

成功返回,並在名爲<div class="announcement_block"></div>周圍格格式化數據,然而問題是,我的JavaScript參考這個元素不起作用。

換句話說,

$(window).load(function() { 
    $(".announcement_block").hover(
       function() { 
       console.log("Did it work?"); 
     $(this).find(".announcement_actions").find(".action_edit").append('<input type="button" onclick="updateAnnouncement($(this).parent().parent())" class="btn btn-info btn-lg" style="font-size: 10pt; width: 2em; padding: 0px; padding-top:5px;" value="Edit">&nbsp;&nbsp;'); 
        $(this).find(".announcement_actions").find(".action_delete").append('<input type="submit" class="btn btn-info btn-lg" style="font-size: 10pt; background-color: #EB5F6B; width: 2.5em; padding: 0px; padding-top:5px;" value="Delete">'); 
       }, function() { 
       $(this).find(".announcement_actions").find(".action_edit").empty(); 
       $(this).find(".announcement_actions").find(".action_delete").empty(); 
       } 
      ); 
}); 

那的代碼塊不起作用。它曾經在HTML正好在for循環中加載時工作。但現在它不再通過Ajax加載了。

無論何時我將鼠標懸停在塊上,都不會運行代碼,因爲console.log從不輸出。

有人可以幫我嗎?謝謝。

回答

3

試試這個:

$(document).on({ 
    mouseenter: function() { 
     //stuff to do on mouse enter 
    }, 
    mouseleave: function() { 
     //stuff to do on mouse leave 
    } 
}, ".selector"); 

很好地回答了類似的問題here