繁体   English   中英

值未从html格式传递到Javascript,变量记录未定义,为什么?

[英]Values not passing from html form to Javascript, variables logging undefined, why?

我正在尝试为班级制作一个小型站点,该站点将根据下拉选择来更改地图。 因为我对lat和long值进行了硬编码,所以第一个地图可以很好地弹出,但是当您使用下拉框时,这些值会返回未定义状态。 我不认为它正确地通过了,我不知道为什么。

 <!DOCTYPE HTML>
<head>
    <meta charset='utf-8'>
    <link href ='style.css' rel='stylesheet' />
    <script async defer src="https://maps.googleapis.com/maps/api/js?key=[hidden]"></script>

    <title>Geolocation</title>
</head>
<body>
    <div id="map"></div>
    <div id="formArea">
        <form>
            <h1>Famous Cities</h1>
            <fieldset>
                <label>Cities</label>
                <select id="selectedCity" name="selectedCity">
                    <option value='None'>Please select a city from the dropdown</option>
                    <option value='ITA'>Rome, Italy</option>
                    <option value='FRA'>Paris, France</option>
                    <option value='USA'>New York, USA</option>
                </select>
            </fieldset>
        </form>
    </div>
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
<script src='script.js'></script>
</body>
</html>

JS文件在下面

var map;

function initMap() {
        var mapDisplay = document.getElementById('map');
        var mapOptions = {
            center: new google.maps.LatLng(40.7484,-73.9857),
        zoom: 8
        };
        map = new google.maps.Map(mapDisplay, mapOptions);

        console.log('now exiting initMap');
}


var coordsLat = {
    'ITA':41.9028,
    'FRA':48.8566,
    'USA':40.7128,
};

var coordsLng = {
    'ITA': 12.4964,
    'FRA': 2.3522,
    'USA': -74.0060
};

function changeSelection(loc) {
    var lac = coordsLat[loc];
    var lgc = coordsLng[loc];
    map.setCenter(new google.maps.LatLng(lac, lgc));
    console.log('selection changed')
    console.log('new coordinates are now: ' + lac +" : " + lgc);
}


$(document).ready(function(){
    $(window).on('load', function(){
    initMap();
    $("#selectedCity").change(changeSelection);

    });
});

之所以如此,是因为您将Event对象传递给changeSelection方法。 您需要传递一个值:

$("#selectedCity").change(function() {
  changeSelection($(this).val());
});

这工作,因为jQuery的设置this处理程序的回调到DOM元素中。 每个jQuery文档

每当您在jQuery集合上调用jQuery的.each()方法或其事件方法之一时,回调函数的上下文(即this)都会被设置为DOM元素。

你在打电话

$("#selectedCity").change(changeSelection);

而您的功能changeSelection需要一个参数

function changeSelection(loc) { ... }

您可能想获取选择的值,因此我建议:

$("#selectedCity").change(function({changeSelection($("#selectedCity").options[$("#selectedCity").selectedIndex].value);});  

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM