简体   繁体   中英

Javascript inside foreach loop

Suppose you have some code which includes a javascript tooltip, and a php foreach ($result as $row) loop which is calling values from an sql database like so,

     <?php

   foreach ($result as $row) {
       $link = $qs->link($row,'item');
       $logoImage = $qs->getLogo($row->file_id);

       echo "<ul class=\"imggrid\"><li><a class=\"ItemLink\" href=\"$link\"><img width=\"80\" height=\"80\" src=\"" . $logoImage . "\" /></a></li></ul>";

?>
<script type="text/javascript">
  jQuery(function() {
    jQuery( document ).tooltip({ hide: "true", show: "false", 
      content: function() {
        if ( jQuery(this).is( "img[src='<?php echo $logoImage ?>']" ) ) {
          return "<img class='map' src='<?php echo $logoImage ?>'><a><?php echo $qs->abbreviate($row->title,50); ?></a>";
        }
              }
    });
  });
  </script>

<?php

   }
   ?>

This is oversimplified but the php spits out a grid of pictures, and I want the tooltip to display a bigger version of each picture as it hovers. Right now it only displays the first picture in the grid for all the pictures. I am assuming it is because the script is outside the loop. But can I throw the script in the foreach loop?

Any suggestions or help would be great. Keep in mind I am a novice at this stuff.

EDIT: I added the part of my code in question.

EDIT 2: Okay I've updated this code but now it is displaying nothing. I thought this would work since I am selecting img elements with src = $logoImage, where $logoImage spits out the address of the file.

foreach ($result as $row) {
  // the echo sentence
  ?>
  <!-- script goes here -->
  <?php
}

Remember that, at any point, you can close the PHP tags and start outputting raw data (eg, HTML) to the page.

I guess the issue could be because of id attribute in your image tags.

You need to generate dynamic ids(may be from DB), for each image and cal the tooltip based on that.

There can not be same id use multiple times a html page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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