2013-04-04 88 views
2

我有一些從mysql提供的內容,點擊時應該發出警報()... 但是,這不起作用...當元素通過mysql顯示時,jquery事件不會觸發

這裏是我是從PHP送入/ get_answers.php

<?php session_start(); ?> 
<?php require_once("../includes/include_all.php"); ?> 
<?php $answers = $question->get_answers_for_question($_GET['id']); ?> 
<?php while($row = $answers->fetch_array()){ ?> 
    <!-- ALL ANSWERS HERE --> 
    <div class = 'answer-row'> 
    <div class = 'answer-side'> 
     <div class = 'arrow-contain-answer' type = 'answer' id = 'arrow-up' answer-id = '<?php echo $row["id"]; ?>'></div> 
     <div class = 'answer-votes-contain'> 
      <?php echo $row['popularity']; ?> 
     </div> 
     <div class = 'arrow-contain-answer' id = 'arrow-down'answer-id = '<?php echo $row["id"]; ?>'></div> 
     </div> 

    <div class = 'answer-content'> 
     <?php 
     echo $row['content']; 
     ?> 
    </div> 

    <div class = 'actions'> 
     <a href = '#' class= 'add-comment' id = '<?php echo $row["id"]; ?>'> add comment </a> 
    </div> 

    </div> 

<?php } ?> 

和這裏的代碼代碼,它顯示在頁面上的jQuery:

$(".arrow-contain-answer").click(function(){ 
    alert(); 
}); 

我想要什麼至發生的時候,有人點擊與'箭頭包含答案'類的元素將發生一個事件..

我想我有問題之前元素是通過mysql/php「喂」到頁面。

+0

你真的具有的屬性和它們的值之間的空間?這是行不通的。 – AndrewR 2013-04-04 08:10:47

+0

nope,當我複製並粘貼我的格式時,所有的時髦...我試圖儘可能清除它 – 2013-04-04 08:11:22

+0

定義html屬性時,不要用空格包圍等號'='。此外,使用雙引號這樣的屬性:'class =「arrow-containing-answer」'而不是'class ='arrow-containing-answer'' – 2013-04-04 08:11:39

回答

4
$(document).on("click", ".arrow-contain-answer", function(){ 
    alert(); 
}); 

試試這種方式來添加動態元素!

+0

lol哇... tnx會很快接受 – 2013-04-04 08:09:57

+0

哦,你能告訴我爲什麼我需要添加$(文檔)嗎? – 2013-04-04 08:10:37

+0

$(「element_selector」)僅在您的元素位於頁面加載時的html代碼上工作,如果在頁面加載後添加,則這是編寫代碼的正確方法。 http://api.jquery.com/on/ – Svetoslav 2013-04-04 08:12:27

1

如果使用與添加動態fed元素時文檔中存在的最接近的靜態元素(父)進行委託,它會更好(performancewise)。

$('.answer-row').on("click", ".arrow-contain-answer", function(){ 
    alert('clicked'); 
}); 

閱讀更多關於on delegated事件

相關問題