2013-04-04 87 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事件

相关问题