当通过mysql显示元素时,不会触发Jquery事件

时间:2013-04-04 08:06:37

标签: php jquery

我有一些内容是从mysql输入的,当点击时应该触发一个alert()... 但是,这不起作用......

这是我从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();
});

我想要发生的是当有人点击带有'arrow-contains-answer'类的元素时,会发生一个事件。

我认为我之前遇到的问题是元素通过mysql / php被“送入”页面。

2 个答案:

答案 0 :(得分:4)

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

尝试使用这种方式添加动态元素!

答案 1 :(得分:1)

如果用最近的静态元素(父级)委托它,当添加动态fed元素时,它会更好(性能)。

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

详细了解on delegated事件