gpt4 book ai didi

javascript - 值没有从 html 表单传递到 Javascript,变量记录未定义,为什么?

转载 作者:行者123 更新时间:2023-12-03 03:05:18 26 4
gpt4 key购买 nike

我正在尝试为类(class)制作一个小型网站,该网站将根据下拉选择更改 map 。第一个 map 弹出得很好,因为我对纬度和经度值进行了硬编码,但是当您使用下拉框时,这些值会返回未定义。我认为它没有被正确通过,我也不明白为什么。

 <!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 doc :

Whenever you call jQuery's .each() method or one of its event methods on a jQuery collection, the context of the callback function — this — is set to a DOM element.

关于javascript - 值没有从 html 表单传递到 Javascript,变量记录未定义,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47189349/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com