javascript - 如何在 while 循环中为每个 div 创建一个 ID 并使用 JQuery 发出警报

标签 javascript php jquery html

我有 2 段来自数据库,它可以工作,没有任何问题。但我添加了一个按钮,当我单击它时,它会提醒该按钮所在的当前 div 的 ID。

现在这是我的 table :

+--------+--------------------+
|   id   |      paragraph     |
|--------+--------------------+
|   1    | this is text 1     |
|   2    | another text       |
+-----------------------------+

我的 PHP 和 HTML 代码:

<?php
  $query = mysql_query(SELECT * FROM tests);
  while($row = mysql_fetch_assoc($query)){ 
  $post_id = $row['id'];
  $text = $row['paragraph'];
?>

<div id='text' class='<?php echo "$post_id";?>'>
  <p><?php echo "$text";?></p>
  <input type='button' value='Show id' id='show'>
</div>

<?php } ?>

现在可能生成了 2 个段落,但是当我单击显示按钮时,即使我单击第二个,它也只会显示 1 个 id:

这是我的 JQuery 代码:

$('#show').click(function(){
   var ids = $("#text").attr('class');
   alert(ids);
});

最佳答案

id="" 属性值应该是唯一的。反过来做:

<div id="<?php echo $post_id; ?>" class='text'>
    <p><?php echo $text; ?></p>
    <input type='button' value='Show id' class='button'>
</div>

jquery

$('.button').click(function(){
   var ids = $(this).parent('div').attr('id');
   alert(ids);
});

Note: Stop using mysql_ functions, instead use mysqli_* or PDO

示例:

<?php

$con = new mysqli('localhost', 'username', 'password', 'database');
$result = mysqli_query($con, 'SELECT * FROM tests');
while($row = $result->fetch_assoc()) {
$post_id = $row['id'];
$text = $row['paragraph'];
?>

<div id="post_<?php echo $post_id; ?>">
    <p><?php echo $text; ?></p>
    <button type="button" class="button">Show</button>
</div>

<?php } ?>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$('.button').click(function(){
   var ids = $(this).parent('div').attr('id');
   alert(ids);
});
</script>

Jeroen 非常重要的一点:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

Reference

关于javascript - 如何在 while 循环中为每个 div 创建一个 ID 并使用 JQuery 发出警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24688145/

相关文章:

javascript - Angular 未捕获引用错误: Service is not defined

javascript - 为什么我的提交表单没有在我的 Meteor 应用程序中执行?

php - Magento Cron Tab 作业时区

php - 按 channel 名称获取 channel 中最受欢迎的视频

javascript - 定位元素但确保它仍在屏幕上

jquery - 获取选中复选框的总数

jquery:在单元格中附加按钮

javascript - React SDK可以在纯JavaScript中使用吗?

javascript - 依次解决 Promise 会导致错误

php - 加载测试 UI