2016-02-22 87 views
0

我正在使用循环从我的数据库中获取数据列表。我循环一个div,但值取决于我在数据库中的变化。我会想要获得我从各个div上点击的链接的id。下面是我的html代码...在jquery上单击时获取循环元素的标识

<?php 
$query = $student->conn->prepare('SELECT * FROM groups'); 
$query->execute(); 
$result = $query -> fetchAll(); 
$count = 0; 
foreach ($result as $row) { 
    $count = $count + 1; 
    $groupName = $row['GpName']; 
    $groupAdmin = $row['GpAdmin']; 
    $groupPurpose = $row['GpPurpose']; 
    $output = "42"; 
    echo "<div class='animated flipInY col-sm-4'> 
       <div class='tile-stats'> 
        <div class='icon'><i class='fa fa-tags'></i></div> 
        <div class='count'>$count</div> 
        <h3 id='groupName'>$groupName</h3> 
        <a id='$groupName' class='display' href='#'><p>Click here display group information.</p></a> 
       </div> 
      </div>"; 
} 
?> 

这是我使用的jQuery代码。它工作在控制台,但它并没有在网页上运行:

$('.display').on('click', function() { 
    $(this).next();  
    var id = $(this).prev().val(); 
    alert(id); 
}); 
+1

看看[this](http://stackoverflow.com/a/3239600/1272394)。 – Drewness

+1

现在你正在创建重复的id('id ='groupName''),这是行不通的。 ID必须是唯一的。 '.display'后面没有'next()'(兄弟)。你可以摆脱那行代码。通常'var id = $(this).prev('h3')。attr('id');'[退出使用alert()进行故障排除。](http://stravid.com/en/stop- -javascript-alert-madness /),请改用'console.log()'。 –

+0

发布呈现的HTML,而不是PHP。 – j08691

回答

0

声明

它可以在控制台中,但它并没有在网页

上工作让我觉得你使用的是Ajax,这意味着你将一个事件绑定到不存在的元素上。因此,在替换内容后使用事件冒泡或绑定事件。

$(document).on('click', '.display', function() { 
    var id = $(this).prev().val(); 
    alert(id); 
}); 
+0

我同意这一点,如果它是一个Ajax请求,你将需要委派。 – CodeGodie