jquery while循环

时间:2016-01-14 00:40:09

标签: javascript jquery html

我想显示每个广告的距离(缩略图)。我正在使用Google Maps JavaScript API。问题是只有第一个广告显示距离,或者,如果我更改了代码,则每个缩略图都会显示每个距离。

当缩略图处于while循环时,如何显示与Google(或jQuery)的距离?非常感谢您的帮助。

以下是代码:

<?php

  include 'includes/db.inc.php'; //Connection to the database.
  include 'includes/login.inc.php'; //Processes the login and the sign up info to fetch the user info in the database.

?>

<!DOCTYPE html>
<html lang="fr">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <meta name="description" content="Vous avez besoin d'un service économique? Trouvez-le sur Jobbinn.">
    <meta name="keywords" content="petites annonces classées, kijiji, Les PACs">
    <meta name="author" content="">
    <link rel="icon" href="images/jobbinn_logo.png" type="image/png" sizes="16x16">
    <title>Jobbinn</title>

    <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css">
    <!-- Custom CSS file -->
    <link href="bootstrap/css/custom.css" rel="stylesheet" type="text/css">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="fonts/css/font-awesome.min.css">
    <!-- stylesheet for index.php (style folder) -->
    <link href="style/index.css" rel="stylesheet" type="text/css">
    <!-- Roboto Condensed Font -->
    <link href='https://fonts.googleapis.com/css?family=Roboto+Condensed:400,700,300' rel='stylesheet' type='text/css'>

  </head>
  <body>

    <?php

      if(isset($_SESSION['email']) && isset($_SESSION['password']) == true) {

        $sel_sql = "SELECT * FROM users WHERE email = '$_SESSION[email]' AND password = '$_SESSION[password]'";

        if($run_sql = mysqli_query($conn, $sel_sql)) {

          if(mysqli_num_rows($run_sql) == 1) {

            include 'includes/dash_header.inc.php';

          }

        }

      } 

    ?>
    <?php include 'includes/header.inc.php'; ?>
    <?php include 'includes/subheader.inc.php'; ?>

    <div id="head">
      <div class="container bring-down">
        <div class="row">
          <div class="col-md-12">
            <h2>Vous avez besoin d'un service économique? </br> Trouvez-le sur Jobbinn.</h2>
            <h4>Trouvez. Achetez. Profitez de la vie.</h4>
            <form class="form-group" action="search.php">
              <input type="search" name="search" class="form-control" placeholder="Que recherchez-vous?">
              <button name="search_submit" type="submit" class="btn btn-danger btn-lg">Trouver un service</button>
              <a id="start" href="startselling.php" class="btn btn-danger btn-lg">Commencer à vendre</a>
            </form>
            <div class="icon-align-right">
              <a href="https://www.facebook.com/sharer/sharer.php?u=http%3A//www.jobbinn.com"><i class="fa fa-facebook-square fa-2x icon-spacing" style="color:#F1F1EC;"></i></a>
              <a href="https://twitter.com/home?status=Quand%20vous%20voulez%20un%20travail%20bien%20fait%20sans%20que%20%C3%A7a%20vous%20co%C3%BBte%20un%20bras.%20http%3A//www.jobbinn.com%20%23mtl"><i class="fa fa-twitter-square fa-2x icon-spacing" style="color:#F1F1EC;"></i></a>
              <a href="https://www.instagram.com/instajobbinn"><i class="fa fa-instagram fa-2x icon-spacing" style="color:#F1F1EC;"></i></a>
              <a href="https://plus.google.com/share?url=http%3A//www.jobbinn.com"><i class="fa fa-google-plus-square fa-2x icon-spacing" style="color:#F1F1EC;"></i></a>
              <a href="https://www.linkedin.com/shareArticle?mini=true&url=http%3A//www.jobbinn.com&title=Quand%20vous%20voulez%20un%20travail%20bien%20fait,%20sans%20payer%20un%20bras.&summary=&source="><i class="fa fa-linkedin-square fa-2x icon-spacing" style="color:#F1F1EC;"></i></a>
            </div>
          </div>
        </div>
      </div>
    </div>


    <div id="thumbnails">
      <div class="container">
        <h2>Services Populaires</h2>
        <h4 style="color:#333;">Choisissez parmi nos services les plus populaires.</h4>
        <div class="row">

          <?php 

            $return_arr = array();
            $sel_sql = "SELECT
                        a_id AS annonce_id,
                        titre AS annonce_titre,
                        image AS annonce_image,
                        price AS annonce_prix,
                        postal_code AS annonce_code,
                        city AS annonce_ville,
                        numcommentaires AS num_commentaires,
                        SUM(communication)+SUM(service)+SUM(recommandation) AS total_rating
                        FROM annonces a
                        INNER JOIN users u
                        ON a.user_id = u.id
                        LEFT JOIN (SELECT 
                          b.ad_id,
                          SUM(communication) AS communication,
                          SUM(service) AS service,
                          SUM(recommandation) AS recommandation,
                          COUNT(id) AS numcommentaires
                          FROM commentaires b
                          GROUP BY b.ad_id) b
                        ON a.a_id = b.ad_id
                        WHERE statut = 'published'
                        GROUP BY a_id
                        LIMIT 20
                       ";

            $conn->set_charset("utf8");
            $run_sql = mysqli_query($conn, $sel_sql);
            while ($rows = mysqli_fetch_assoc($run_sql)) {

              $return_arr[] = $rows['annonce_code'];

              echo '

              <div class="col-xs-12 col-md-4">
                <div class="thumbnail">
                  <a href="annonce.php?post_id='.$rows['annonce_id'].'">
                    <input class="tid" type="hidden" name="annonceid" value="'.$rows['annonce_id'].'">
                    <input class="tid" type="hidden" name="annoncecode" value="'.$rows['annonce_code'].'">
                    <p>'.$rows['annonce_titre'].'</p>
                    <img src="'.$rows['annonce_image'].'" alt="image">
                    <div class="caption">
                      <div>
                        <h3 style="color:#05C33C; font-weight:bold;">'.$rows['annonce_prix'].'$</h3>
                        <p style="color:#FE6E32;">'.($rows['num_commentaires'] == '' ? 'nouveau' : ''.substr($rows['total_rating'] / $rows['num_commentaires'] / 3,0,3).'/10 ('.$rows['num_commentaires'].')').'</p>
                        <p>'.$rows['annonce_ville'].'</p>
                        <p class="distance-'.$rows['annonce_id'].'"></p>
                      </div>
                    </div>
                  </a>
                </div>
              </div>

              ';

            }

            $postal = json_encode($return_arr);

          ?>
        </div>
      </div>
    </div>

    <div id="bottom-container" class="container profile text-center">
      <div class="row">
        <div class="col-md-4 col-xs-12">
          <img src="images/icon_graph.png" class="img-circle">
          <h3>Faites avancer les choses</h3>
          <p>Des gens qui aiment se qu'ils font vous aident à tout faire à un prix imbattable.</p>
        </div>
        <div class="col-md-4 col-xs-12">
          <img src="images/icon_money.png" class="img-circle">
          <h3>Offrez vos services</h3>
          <p>Qu'est-ce que vous faites de mieux? Créez votre annonce et commencez à vendre. C'est gratuit et ça prend seulement 5 minutes.</p>
        </div>
        <div class="col-md-4 col-xs-12">
          <img src="images/icon_gears.png" class="img-circle">
          <h3>Confiance et sécurité</h3>
          <p>Votre sécurité est notre top priorité. Des transactions sécuritaires et notre équipe vous protègent en tout temps.</p>
        </div>
      </div>
    </div>

    <footer>
      <?php include 'includes/footer.inc.php'; ?>
    </footer>

    <script src="js/jquery.js"></script>
    <script src="bootstrap/js/bootstrap.min.js"></script>
    <script src="scripts/index.js"></script>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
    <script type="text/javascript">

      $.each($(".thumbnail"), function() {

        $this = $(this);
        id = $this.find('input[name="annonceid"]').val();
        code = $this.find('input[name="annoncecode"]').val();
        //$this.find('input[name="annonceid"]').val(text);
        $(".distance-" + id).text(code + "/" + id);

        var service = new google.maps.DistanceMatrixService(); //Creates a new request to the API
          service.getDistanceMatrix({
          origins: ['"' + code + '"'], //The seller side
          destinations: ["J7Z 7B9"], //The buyer side
          travelMode: google.maps.TravelMode.DRIVING,//Can have multiple travel mode like driving, cycling and walking
        }, callback);

        function callback(response, status) { //We get a document in JSON format
          if (status == google.maps.DistanceMatrixStatus.OK) {
            var origins = response.originAddresses;
            var destinations = response.destinationAddresses;
            for (var i = 0; i < origins.length; i++) {
              var results = response.rows[i].elements;
              for (var j = 0; j < results.length; j++) {

                var element = results[j];
                var distance = element.distance.text; //The distance between the origin and a destination
                var duration = element.duration.text; //The time it takes to get there
                var from = origins[i];
                var to = destinations[j];

                console.log(element);
                console.log(distance);
                console.log(duration);
                console.log(from);
                console.log(to);

              }
            }
          }
        }
      });

    </script>

  </body>
</html>

1 个答案:

答案 0 :(得分:0)

HTML中的id属性必须符合spec的唯一性。因此,jQuery将假设您操作#distance时只有一个元素。这将使您看到只有第一个元素具有所需结果的行为。

要解决此问题,您只需将行ID作为ID的一部分:#distance-1#distance-2等。