我有 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 usemysqli_*
orPDO
示例:
<?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 (".").
关于javascript - 如何在 while 循环中为每个 div 创建一个 ID 并使用 JQuery 发出警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24688145/