douyousu9691
2015-03-19 12:45
浏览 266
已采纳

jquery:循环遍历类似的div

I'm not that good with jQuery/Javascript, but I'm sure the following is possible, but don't know how I should start doing it.

I'm using the Google Maps API. In WordPress I have severel posts, where I have mentioned the address in the content of it.

Now, I output the addresses with a simple loop, but what I'm trying to do is read those addresses with jQuery, to put them in an array and show them on the map.

Currently it is only showing the first address it has encountered, but I actually need to loop through every div with <div class="address"></div>:

Here's what my PHP/HTML looks like:

        <?php

            $kantorenArgs = array(

                'post_type' => 'kantoren',
                'posts_per_page' => '4'

            );

            $kantoren = new WP_Query($kantorenArgs);

            if ($kantoren->have_posts()) :

                while ($kantoren->have_posts()) : $kantoren->the_post(); ?>

                <li class="office">

                    <a href="<?php the_permalink(); ?>">

                        <?php the_title(); ?>

                        <div class="address"><?php the_content(); ?></div>

                    </a>

                </li>

                <?php

                endwhile;

            endif;

        ?>

And this is the jQuery that I'm using:

    jQuery(document).ready(function () {

        (function($) {

          $.get_addresses = function() {

            var address = $(".address").html();

            return address;

          }
        })(jQuery);

        var map;
        var elevator;
        var myOptions = {
            zoom: 8,
            center: new google.maps.LatLng(50.9660922, 4.5574837),
            mapTypeId: 'roadmap'
        };
        map = new google.maps.Map($('#map_canvas')[0], myOptions);

        var addresses = [$.get_addresses()];

        for (var x = 0; x < addresses.length; x++) {
            $.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x]+'&sensor=false', null, function (data) {
                var p = data.results[0].geometry.location
                var latlng = new google.maps.LatLng(p.lat, p.lng);
                new google.maps.Marker({
                    position: latlng,
                    map: map
                });

            });
        }

    });

Thanks for the help!

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

相关推荐 更多相似问题