简体   繁体   English

脚本仅返回从php数据库中获取的第一个值的ID

[英]Script only returns the id of first value fetched from database in php

<?php 

    include "connection.php";
    $query="select n_id,title,news from news ";
    $queryr=$con->query($query);
    while($row=$queryr->fetch_assoc())
    {
    ?>

<?php echo $row['title'];?>
<a href="#" id="readmore">... Read More</a>
<input type="hidden" id="idd" name="idd" value="<?php echo $row['n_id'];?>" >
<?php } ?> 

Here is my php code that retrieves values from database. 这是我的php代码,可从数据库中检索值。 I want to alert the id of each row . 我想提醒每一行的ID。 Below is my script : 以下是我的脚本:

<script>
    $(document).ready(function(){

      $("#readmore").click(function(){
         var id=$("#idd").val();
          alert(id);

    });

    });
</script>

At present I am only getting the id of first value fetched from database. 目前,我只从数据库中获取第一个值的ID。 How it is possible with the rest of the values? 其余的值怎么可能? Thanks in advance. 提前致谢。

Use class selector instead of id . 使用class选择器代替id id supposed to be unique. id应该是唯一的。 You can not have same id for multiple elements. 多个元素不能具有相同的id In this case class will work perfectly. 在这种情况下, class将完美运行。

<a href="#" class="readmore">... Read More</a>
<input type="hidden" class="idd" name="idd" value="<?php echo $row['n_id'];?>" >

$(".readmore").click(function(e){
    e.preventDefault(); // Only if you dont want it to reload
    var id=$(this).next('.idd').val();
    alert(id);
});

FIDDLE 小提琴

ID needs to be unique: ID必须是唯一的:

Change to class="readmore" and input's class="idd" and use 更改为class =“ readmore”并输入class =“ idd”并使用

 $(".readmore").click(function(e){
   e.preventDefault()
   var id=$(this).next(".idd").val();
   alert(id);
 });

Alternatively do this: 或者执行以下操作:

<?php echo $row['title'];?>
<a href="#" class="readmore" data-id="<?php echo $row['n_id'];?>">... Read More</a>
<?php } ?> 

using 运用

 $(".readmore").click(function(e){
   e.preventDefault()
   var id=$(this).data("id");
   alert(id);
 });

Use jquery each function like this 使用jQuery这样的每个功能

$('.readmore').each(function(e) {
    e.preventDefault();
    var id = $(this).next('.idd').val();
    alert(id);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM