清理JavaScript代码以创建动态HTML

时间:2014-01-28 14:52:03

标签: javascript

我正在使用JavaScript动态创建大量内容,现在我认为我的代码看起来很糟糕。我正在寻找一种方法来清理它,所以如果有人有一些建议可以更好地复制我正在做的事情,我很乐意听到它。感谢

var nearestContent = "<h2>Nearest Dealers:</h2>" + "<h3>" + nearest[0][2] + "</h3><p>" + nearest[0][1] + "<BR />" + nearest[0][3] + ", " + nearest[0][4] + ' ' + nearest[0][5] + "<BR />" + milesAway + " Miles away!" + 
                             "<BR />" + "<a href='" + nearest[0][6] + "'>" + nearest[0][6] + "</a>" + "</p>";                            
document.getElementById("NearestLocation").innerHTML=nearestContent;

这是我的maps.js文件:

    var markers = new Array();
    var infoWindowContent = [];
    var geocoder;
    var map;
    var result;
    var nearest = new Array();



        function initialize() {
            for (var i = 0; i < data.Latitude.length; i++)
            {
                markers[i] = [(data.Latitude[i]), (data.Longitude[i]), 
                              (data.Address[i]), (data.Company[i]), 
                              (data.City[i]), (data.State[i]),
                              (data.Website[i]), (data.Group[i]), (data.Zip[i])];
            }       

            var icon;
            var bounds = new google.maps.LatLngBounds();
            var mapOptions = {
                mapTypeId: 'roadmap'
            };
            geocoder = new google.maps.Geocoder();

            // Display a map on the page
            map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
            map.setTilt(45);

            // Info Window Content
            for(i=0; i< markers.length; i++) {
                var testContent = ['<div class="info_content">' + '<h3>' + markers[i][3] + '</h3>' + '<p>' + markers[i][2] + '<BR />' + markers[i][4] + ', ' + markers[i][5] + ' ' + markers[i][8] + '</p>' + '<BR /> <a href="' + markers[i][6] +'">' + markers[i][6] +'</a>' +'</div>'];
                infoWindowContent.push(testContent);
            }
            // Display multiple markers on a map
            var infoWindow = new google.maps.InfoWindow(), marker, i;

            // Loop through our array of markers & place each one on the map  
            for( i = 0; i < markers.length; i++ ) {
                var position = new google.maps.LatLng(markers[i][0], markers[i][1]);
                switch (markers[i][7]) {
                    case "Mobile Showroom":
                        icon = "red-dot";
                        break;
                    case "NS Dealer":
                        icon = "blue-dot";
                        break;
                    case "SD Dealer":
                        icon = "yellow-dot";
                        break;
                    case "S Dealer":
                        icon = "green-dot";
                        break;
                    default:
                        icon=   "orange-dot";
                        break;
                }
                icon = "mapIcons/" + icon + ".png";
                bounds.extend(position);
                marker = new google.maps.Marker({
                    position: position,
                    map: map,
                    icon: new google.maps.MarkerImage(icon, null, null, null, new google.maps.Size(20, 20)),
                    title: markers[i][2]
                });

                // Allow each marker to have an info window    
                google.maps.event.addListener(marker, 'click', (function(marker, i) {
                    return function() {
                        document.getElementById("DealerInfo").innerHTML=infoWindowContent[i][0];
                    };
                })(marker, i));

                // Automatically center the map fitting all markers on the screen
                map.fitBounds(bounds);
            }
        }




        function codeAddress() {
          var address = document.getElementById('address').value;
          geocoder.geocode( { 'address': address}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                result = results[0].geometry.location;
                map.setZoom(8),
                map.setCenter(results[0].geometry.location);
                CalculateNearestDealer(results[0].geometry.location);
              var marker = new google.maps.Marker({
                  map: map,
                  icon: "mapIcons/beachflag.png",
                  position: results[0].geometry.location
              });

            } else {
              alert('Geocode was not successful for the following reason: ' + status);
            }
          });
        }





        function CalculateNearestDealer(results) {
        for (var i = 0; i < data.Latitude.length; i++)
        {
            var markers = [(data.Latitude[i]), (data.Longitude[i]), 
                          (data.Address[i]), (data.Company[i]), 
                          (data.City[i]), (data.State[i]),
                          (data.Website[i])];
            var userLocation = new google.maps.LatLng(result.ob, result.pb);
            var dealerLocation = new google.maps.LatLng(markers[0], markers[1]);
            var distance = google.maps.geometry.spherical.computeDistanceBetween(userLocation, dealerLocation);
                nearest[i] = [(distance/1609.344), (data.Address[i]), (data.Company[i]), (data.City[i]), (data.State[i]), (data.Zip[i]), (data.Website[i])];
        }

        nearest.sort(function(a,b){return a[0]-b[0];});
        var milesAway = Math.round( nearest[0][0] );
        var nearestContent = Mustache.render("<h2>Nearest Dealers:</h2><h3>{{dealerName}}</h3>"
            + "<p>{{description}}<br/>{{info1}}, {{info2}}<br/>{{distance}} Miles away!<br/><a href='{{href}}'>{{hrefTitle}}</a></p>", {
            dealerName: nearest[0][2],
            description: nearest[0][1],
            info1: nearest[0][3],
            info2: nearest[0][4],
            href: nearest[0][6],
            hrefTitle: nearest[0][6],
            distance: milesAway
        });
        document.getElementById("NearestLocation").innerHTML=nearestContent;
        document.write("<p>" + nearest[0] + "</p>");
   }

HTML文件:

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Simple markers</title>
    <link rel="stylesheet" href="css/style.css" />
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&v=3&libraries=geometry"></script>
    <script type="text/javascript" src="js/mustache.js"></script>
    <script type="text/javascript" src="js/maps.js"></script>

    </head>

<body>
    <div id="container">
    <div id="map_canvas"></div>
    <?php

        require 'DB.php';

        $stmt = "SELECT dealerinfo.Company, small.Address, dealerinfo.City, dealerinfo.State, dealerinfo.Phone, dealerinfo.Zip, dealerinfo.Website, small.Lat, small.Long, dealerinfo.Group
                 FROM small
                 LEFT JOIN dealerinfo ON small.Address = dealerinfo.Address
                 ORDER BY small.Address";

        $corodinates = array();
        $i = 0;
        foreach($DB->query($stmt) as $row) {

            $corodinates['Latitude'][$i] = $row['Lat'];
            $corodinates['Longitude'][$i] = $row['Long'];
            $corodinates['Address'][$i] = $row['Address'];
            $corodinates['Company'][$i] = $row['Company'];
            $corodinates['City'][$i] = $row['City'];
            $corodinates['State'][$i] = $row['State'];
            $corodinates['Zip'][$i] = $row['Zip'];
            $corodinates['Website'][$i] = $row['Website'];
            $corodinates['Group'][$i] = $row['Group'];
            $corodinates['Phone'][$i] = $row['Phone'];
            $i++;
        }
    ?>

    <div id="CustomerAddress">
        <input type="textbox" id="address"/>
        <input type="button" value="Locate" onclick="codeAddress()">
    </div>

    <div id="DealerInfoContainer">
        <div id="NearestLocation"></div>
            <div id="DealerInfo">
                <h2>Test Dealer Network</h2>
                <p>Please enter the location of customer above or click a marker to view information about dealer.</p>
            </div>
        </div>
    </div>
    <script>var data = <?php echo json_encode($corodinates); ?>;</script>
    <script>initialize();</script>
</body>

</html>

2 个答案:

答案 0 :(得分:1)

将JS数据合并到HTML中最好使用模板引擎进行处理。

使用占位符创建数据值的HTML“模板”,然后使用引擎生成您希望通过用数据替换这些占位符来发布的HTML。

您可能需要查看

或者,确实是任何主要的JS开发框架,因为它们往往包含某种形式的模板引擎。

答案 1 :(得分:1)

看起来你应该研究模板。

例如,使用Mustache,它可能如下所示:

var nearestContent = Mustache.render("<h2>Nearest Dealers:</h2><h3>{{dealerName}}</h3>"
    + "<p>{{description}}<br/>{{info1}}, {{info2}}<br/>{{distance}} Miles away!<br/><a href='{{href}}'>{{hrefTitle}}</a></p>", {
    dealerName: nearest[0][2],
    description: nearest[0][1],
    info1: nearest[0][3],
    info2: nearest[0][4],
    href: nearest[0][6],
    hrefTitle: nearest[0][6],
    distance: milesAway
});
document.getElementById("NearestLocation").innerHTML=nearestContent;

这是demo