如何使用javascript在html循环中获取动态id的值?

I am creating a drag and drop system using redips javascript.

This is my script using html and php to generate the data

<div id="base">  
   <table>
     <tbody>
       <?php 
          foreach($deviceID as $row)
          { 
             echo '<tr><td><div class="drag">'.$row['description'].'<input type="hidden" id="bus" value="'.$row['description'].'"></div></td></tr>'; 
          }
        ?>
       </tbody>
    </table>
</div>

This is the fragment of my javascript file.

var redips_init;
redips_init = function () {
    // reference to the REDIPS.drag
    var rd = REDIPS.drag;
    // initialization
    rd.init();
        rd.drop_option = 'shift';
    rd.animation_shift = true;

        rd.myhandler_dropped = function () {            
            alert($('#bus').val());
        }
};

I am not good with php but what i usually do in jsp is create a local index variable and append it to each of the ID attribute in the loop.

So your code would look something like this

  <?php 
      $index=0;    
      foreach($deviceID as $row)
          { 
             echo '<tr><td><div class="drag">'.$row['description'].'<input type="hidden" id="bus'.$index++.'" value="'.$row['description'].'"></div></td></tr>'; 
          }
        ?>

In javascript, your dragAndDrop event should return an index location by which u can get appropriate value.

Now you can use this dynamic ID in your JavaScript to do whatever you want to do.

REDIPS.drag contains save_content() method to scan all DIV elements in a table and to return the result as Query string or JSON object. Input parameters are table id and type of returned result (default is query string). If this is not good enough, you can search for save_content() source and make customization. Method is simple and it uses several loops to scan table content.

On the other hand, if you need to know ID of dropped DIV element that can be written inside myhandler_dropped event hander. Here is code snippet:

rd.myhandler_dropped = function () {
    // define DIV id
    var id = rd.obj.id;
    // write DIV id to the console
    console.log(id)
};

Hope this answer will be helpful.