单击Ajax可排序表的一行时如何打开信息窗口

时间:2012-05-31 07:14:50

标签: php javascript google-maps javascript-events google-maps-api-3

我在here问过类似但不一样的东西(已经回答了)。现在我有一些跟进问题,我认为最好再问一下(我已经阅读了规则,我希望我不会破坏任何规则。但如果我愿意,请提醒我)。

我从MySQL表中加载了几个城市的id,名称和位置,然后将其填充到HTML表格中。还有一个谷歌地图,标记指向这些城市。

当用户点击其中一个HTML行(tr标签)时,我希望在城市标记上弹出一个信息窗口。我在没有任何jQuery的情况下使用PHP,Javascript和XML。我已经做到了这一点。

现在我正在尝试使HTML表格可以排序。因此,当用户点击th时,数据将根据被点击的数据进行排序(但是,对于此示例,它只能按ID排序)。

问题是在它至少排序一次后,单击tr时信息窗口不再弹出。

我的HTML:

<?php
   $query = "SELECT id, name, lat, lng FROM city ORDER BY id";
   $arrCities = mysql_query ($query);
?>

<div id="gmap" style="width: 550px; height: 450px"></div>

<table id="tblData">
   <tr>
       <th>/* when the th clicked it'll call js function */
             <a href="javascript:GetData('sort.php?by=id&val=<? echo $val; ?>', 'tblData');">ID</a>
       </th>
       <th>City</th>
   </tr>

   <?php while ($row = mysql_fetch_assoc($arrCities)) { ?>

       <tr id="<?php echo $row['id']; ?>">

           <td><?php echo $row['id']; ?></td>
           <td><?php echo $row['name']; ?></td>

       </tr>
   <?php } ?>
</table>

我的PHP用于创建填充标记的XML(my-xml-generator.php):

<?php
    $query = "SELECT id, name, lat, lng FROM city ORDER BY id";
    $arrCities = mysql_query ($query);

    $dom = new DOMDocument('1.0', 'utf-8');
    $node = $dom->createElement ('markers');
    $parNode = $dom->appendChild ($node);

    header('Content-type: text/xml');

    while ($row = mysql_fetch_assoc($arrCities))
    {
            $node = $dom->createElement ('marker');
            $newNode = $parNode->appendChild ($node);
            $newNode->setAttribute ('id', $row['id']);
            $newNode->setAttribute ('name', $row['name']);
            $newNode->setAttribute ('lat', $row['lat']);
            $newNode->setAttribute ('lng', $row['lng']);
    }

    echo $dom->saveXML();
?>

我的Google Maps Javascript:

    var gmap = new google.maps.Map (mapDiv, options);

    var arrMarkers = []; 
    var infoWindow = new google.maps.InfoWindow;

    // add markers to the map
    DownloadUrl ("my-xml-generator.php", function(data)
    {
        var xml = data.responseXML;
        var markers = xml.documentElement.getElementsByTagName ("marker");

        for (var i = 0; i < markers.length; i++)
        {
            var id = markers[i].getAttribute("id");

            var lat = parseFloat (markers[i].getAttribute("lat"));
            var lng = parseFloat (markers[i].getAttribute("lng"));
            var pos = new google.maps.LatLng (lat, lng);


            var markerOptions =
            {
                position    : pos,
                map         : gmap,
                draggable   : false
            };

            // add the marker
            var marker = new google.maps.Marker (markerOptions);
            arrMarkers.push(marker);

            // assign onclick event for each tr
            // this is the part that I have to somehow re-run after the sorting is done
            var tr = document.getElementById(id);
            google.maps.event.addDomListener (tr, "click",
                (function(i) {
                    var row = i;
                    return function() {
                        RowClick (row);
                    }
                })(i)
            );


            // add info window
            var html = '<div>' + id + '</div>';

            BindInfoWindow (marker, gmap, infoWindow, html);
        }
    });


    function BindInfoWindow (marker, map, infoWindow, html)
    {
        google.maps.event.addListener (marker, "click", function()
        {
            infoWindow.setContent (html);
            infoWindow.open (map, marker);
        });
    }


    function RowClick (i)
    {
        google.maps.event.trigger (arrMarkers[i], "click");
    }


    function DownloadUrl (url, callback)
    {
        var xhr = new XMLHttpRequest();

        xhr.onreadystatechange = function()
        {
            if (xhr.readyState == 4)
            {
                xhr.onreadystatechange = DoNothing;
                callback(xhr, xhr.status);
            }
        };

        xhr.open ('GET', url, true);
        xhr.send (null);
    }

    function DoNothing() {}

我的GetData()函数(简单和常用):

function GetData (dataSource, divID)
{
    var xhr = new XMLHttpRequest();

    xhr.open ("GET", dataSource);

    xhr.onreadystatechange = function()
    {
        if (xhr.readyState === 4)
        {               
                var targetDiv = document.getElementById (divID);
                targetDiv.innerHTML = xhr.responseText;
        }
    }

    xhr.send (null);
}

我的sort.php(我的排序方式是再次运行查询以检索所需的排序结果并将tr行输出到表的innerHTML):

<?php
   $by = $_GET['by'];
   $val = $_GET['val'];

   $query = "SELECT id, name, lat, lng FROM city ORDER BY $by $val";
   $arrCities = mysql_query ($query);

   // set the new order value
   $val == 'ASC' ? 'DESC' : 'ASC';
?>

   <tr>
       <th>
             <a href="javascript:GetData('sort.php?by=id&val=<? echo $val; ?>', 'tblData');">ID</a>
       </th>
       <th>City</th>
   </tr>

   <?php while ($row = mysql_fetch_assoc($arrCities)) { ?>

       <tr id="<?php echo $row['id']; ?>">

           <td><?php echo $row['id']; ?></td>
           <td><?php echo $row['name']; ?></td>

       </tr>
   <?php } ?>
</table>

单击tr时,该tr中包含的城市的信息窗口将正确弹出。排序也有效

但是在它被排序一次之后,tr的点击事件显然已经消失了。如何在分类后重新分配它?

1 个答案:

答案 0 :(得分:1)

  1. 存储标记的ID。
  2. 封装JS,负责将标记绑定到行。
  3. DownloadUrl回调和GetData函数中调用封装的JS。
  4. 商店ID

    将arrMarkers设为对象:var arrMarkers = {};

    封装绑定

    function BindMarkerRows() {
    
        for(var id in arrMarkers) {
            var tr = document.getElementById(id);
    
            google.maps.event.addDomListener (tr, "click",
                (function(marker) {
                    return function() {
                        google.maps.event.trigger (marker, "click");
                    }
                })(arrMarkers[id])
            );
        }
    }
    

    更新DownloadUrl

    DownloadUrl ("my-xml-generator.php", function(data) {
    
        var xml = data.responseXML;
        var markers = xml.documentElement.getElementsByTagName ("marker");
    
        for (var i = 0; i < markers.length; i++) {
    
            var id = markers[i].getAttribute("id");
    
            var lat = parseFloat (markers[i].getAttribute("lat"));
            var lng = parseFloat (markers[i].getAttribute("lng"));
            var pos = new google.maps.LatLng (lat, lng);
    
    
            var markerOptions =
            {
                position    : pos,
                map         : gmap,
                draggable   : false
            };
    
            // add the marker
            var marker = new google.maps.Marker (markerOptions);
            arrMarkers[id] = marker; //Here we access the object as an associative array
        }
    
        BindMarkerRows();
    }
    

    更新GetData

    function GetData (dataSource, divID)
    {
        var xhr = new XMLHttpRequest();
    
        xhr.open ("GET", dataSource);
    
        xhr.onreadystatechange = function()
        {
            if (xhr.readyState === 4)
            {
                var status = xhr.status;
    
                if ((status >= 200 && status < 300) || status === 304)
                {
                    var targetDiv = document.getElementById (divID);
                    targetDiv.innerHTML = xhr.responseText;
                    BindMarkerRows();
                }
            }
        }
    
        xhr.send (null);
    }