JQuery事件监听器没有触发 - Phonegp / Google Maps

时间:2015-02-07 12:21:34

标签: javascript jquery google-maps cordova

我正在尝试将一个事件监听器绑定到所有带有该类的标签' chatButton'。我正在使用jquery选择器" $(' .chatButton')"但什么也没发生。我正在尝试在创建infowindows之后绑定此侦听器。请参阅以下代码:

<!DOCTYPE html>
<head>
    <title>Title</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <link rel="stylesheet" href="css/themes/custom.css" />
    <link rel="stylesheet" href="css/themes/jquery.mobile.icons.min.css" />
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.3/jquery.mobile.structure-1.4.3.min.css" />
    <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
    <script src="http://code.jquery.com/mobile/1.4.3/jquery.mobile-1.4.3.min.js"></script>
    <script src="js/config.js"></script>
    <script src="js/quickblox.js"></script>
    <script src="js/FileSaver.min.js"></script>
    <style>
        html, body, #map-canvas {
            height: 100%;
            margin: 0px;
            padding: 0px;
        }
    </style>
    <script type="text/javascript"
            src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD86ZDzTPegHkzId5kaN1LHtb7_YMh9KNU">
   </script>

   <script>
        function loadXMLDoc(filename) {
            if (window.XMLHttpRequest)
              {
              xhttp=new XMLHttpRequest();
              }
            else // code for IE5 and IE6
              {
              xhttp=new ActiveXObject("Microsoft.XMLHTTP");
              }
            xhttp.open("GET",filename,false);
            xhttp.send();
            return xhttp.responseXML;
        }
   </script>
   <script type="text/javascript">
        $(document).ready(function () {
            var location;
            var lat;
            var lon;
            var user = window.localStorage.getItem("user"); 
            var sports = window.localStorage.getItem("sports");
            var onSuccess = function (position) {
                lat = position.coords.latitude;
                lon = position.coords.longitude;

                console.log(lat + ", " + lon);

                window.localStorage.setItem("lat", lat);
                window.localStorage.setItem("lon", lon);

                $.support.cors = true;
                $.post("http://www.domain.co.uk/API/location.php", { user: user, lat: lat, lon: lon }, function (data) {
                    initialize();
                });
            };

            // onError Callback receives a PositionError object
            //
            function onError(error) {
                alert('code: ' + error.code + '\n' +
                        'message: ' + error.message + '\n');
            }
            navigator.geolocation.getCurrentPosition(onSuccess, onError);
        });

        function downloadUrl(url,callback) {
            var request = window.ActiveXObject ?
                 new ActiveXObject('Microsoft.XMLHTTP') :
                 new XMLHttpRequest;

            request.onreadystatechange = function() {
                if (request.readyState === 4) {
                    //request.onreadystatechange = doNothing;
                    callback(request, request.status);
                }
            };
            request.open('GET', url, true);
            request.send(null);
        }

        function initialize() {
            var userLat = window.localStorage.getItem("lat");
            var userLon = window.localStorage.getItem("lon");
            var mapOptions = {
              center: new google.maps.LatLng(userLat, userLon),
              zoom: 12
            };
            var map = new google.maps.Map(document.getElementById('map-canvas'),
                mapOptions);
            drawMarkers(map);
        }

        function drawMarkers(map){
            var url = "http://www.domain.co.uk/API/userLocations.xml"
            var infoWindow = new google.maps.InfoWindow;
            downloadUrl(url,function(data){
                var xml=data.responseXML;
                console.log("XML From Server: ", xml);
                var markers = xml.getElementsByTagName("marker");
                for (var i = 0; i < markers.length; i++) {
                  var user = markers[i].getAttribute("user");
                  var sports = markers[i].getAttribute("sports");
                  var image = {
                    size: new google.maps.Size(71, 132),
                    origin: new google.maps.Point(0, 0),
                    scaledSize: new google.maps.Size(71, 132)
                  };
                  var point = new google.maps.LatLng(
                      parseFloat(markers[i].getAttribute("lat")),
                      parseFloat(markers[i].getAttribute("lon")));
                  var html = "<b>" + "Name:<br>" + user + "</b> <br>" + "Sports:<br>" + sports +"<br><br>" + "<a class='chatButton' id="+user+">Chat To User</a>";
                  var marker = new google.maps.Marker({
                      map: map,
                      position: point,
                      title: name
                  });
                  console.log(user, sports, point, html);
                  bindInfoWindow(marker, map, infoWindow, html);
                $(".chatButton").click(function(){
                    console.log("Ev listener fired...");
                    var usr = $(this).attr('id');
                    window.localStorage.setItem("chatToUser", usr);
                    window.location("chat.html");
                });
    }

        });
    }

    function bindInfoWindow(marker, map, infoWindow, html) {
        google.maps.event.addListener(marker, 'click', function() {
        infoWindow.setContent(html);
        infoWindow.open(map, marker);
    });
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body onload="initialize()">
    <div style="max-width:90%;max-height:90%;margin:auto;">
        <div style="width:100%;">
            <h1 style="text-align:center;">Heading</h1>
        </div>
        <div style="width:90%;margin-left:auto;margin-right:auto;">
            <div id="map-canvas" style="width:100%;height:400px"></div>
            <p style="text-align:center;word-wrap:normal;">Tap A User's Pin To See Their Activities and Get In Touch With Them!</p>
        </div>
    </div>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

问题是你初始化一个没有插入dom的元素(chatButton)的监听器,你可以使用live(http://api.jquery.com/live/)为你的点击监听器或初始化和domready-信息窗口的监听器,例如:

function bindInfoWindow(marker, map, infoWindow, html) {

    google.maps.event.addListener(marker, 'click', function() {

      infoWindow.setContent(html);
      infoWindow.open(map, marker);

      google.maps.event.addListener(infoWindow, 'domready', function() {

          $(".chatButton").click(function(){
              console.log("Ev listener fired...");
              var usr = $(this).attr('id');
              window.localStorage.setItem("chatToUser", usr);
              window.location("chat.html");
          });

      });

    });
}

参考:Google maps infowindow events on open