George_Fal 2015-10-17 14:03 采纳率: 0%
浏览 9

如何选择编号

I have a problem on selecting an id on div. I use a while loop on my div.
So i'am creating a unique ID using the id row on my sql. My question is, is it possible to select the id using Javascript? I use bootstrap modal to update my information details (i dont actually know how to ask this question because my english is poor).

example:

while($row = mysqli_fetch_array($result)) { 
    <div id="'details-'<?php echo $row['Room_ID'];?>">
    //code
    </div>
}
  • 写回答

2条回答 默认 最新

  • helloxielan 2015-10-17 14:10
    关注

    To fix your Php code:

    while($row = mysqli_fetch_array($result)) { 
       echo "<div id='details-" . $row['Room_ID'] ."'>";
           // CODE
       echo "</div>";
    }
    

    The problem you got in the id, where you stopped the value by ' already, so the result was something like:

    <div id='details-'28>//Code</div> and fixed to <div id='details-28'>//Code</div>

    and to select the ID with pure JavaScript use document.getElementById( ID )

    If you are not sure of the ID and you just wanna select all items, add a class to the item and select them all by document.getElementsByClassName

    So to select all your stuff by javascript:

    1) Add into your PHP code class called "details" 2) Create a javascript to select all items with the class name "details" 3) Do a foreach loop for the selected items and split them by "-" to devide the "details" from the actual ID 4) Do whatever you want now with the ID

    Practical showcase:

    Php:

    while($row = mysqli_fetch_array($result)) { 
       echo "<div class='details' id='details-" . $row['Room_ID'] ."'>";
           // CODE
       echo "</div>";
    }
    

    JavaScript:

    <script>
    var itemDetails = document.getElementsByClassName("details");
    
    for(var i = 0; i < itemDetails.length; i ++) {
        var ID = itemDetails[i].getAttribute("id").split("-")[1]; 
        // Now you got the ID stored in the variable ID
    </script>
    

    Here you got an example on JSFiddle

    评论

报告相同问题?