为何HTML下拉菜单选中的选项会消失?技术排查请求
问题:下拉菜单选中选项点击后消失
我开发了一款应用,用户可从HTML下拉菜单选择国家,点击按钮后会调用API返回该国的统计信息等数据。但出现一个问题:选中的选项会从下拉菜单中完全消失。
(我知道代码有待优化!我只需要知道下拉菜单选项为何被删除)
触发按钮的函数代码:
function handle() { var dropdown = document.getElementById("countries"); var selectedCountry = dropdown.options[dropdown.selectedIndex]; countryCode = $('#countries').val(); highlightBorders(countryCode); // handle Wikipedia links $('#txtWiki').attr('href', 'https://en.wikipedia.org/wiki/' + selectedCountry) $('#txtWiki').html(selectedCountry) $.ajax({ url: "libs/php/getCountryInfo.php", type: 'POST', beforeSend: function() { $('#loader').show() }, complete: function() { $('#loader').hide() }, data: { country: countryCode }, success: function(result) { console.log(JSON.stringify(result)); if (result.status.name == "ok") { $('#txtContinent').html(result['data'][0]['continentName']); $('#txtCurrency').html(result['data'][0]['currencyCode']); $('#txtCountryName').html(result['data'][0]['countryName']); $('#txtPopulation').html(result['data'][0]['population']); $('#txtCapital').html(result['data'][0]['capital']); } }, error: function(jqXHR, textStatus, errorThrown) { console.error('error retrieving country information') $('#loader').hide() } }); const flagImage = document.getElementById('flagImage'); const flagImageUrl = `flagspng/${countryCode}.png`; flagImage.src = flagImageUrl; const capitalCities = 'capitals/capLatLng.json'; fetch(capitalCities) .then(response => response.json()) .then(data => { // Retrieve the capital city data for the selected country const capitalCityData = data[countryCode]; if (capitalCityData && capitalCityData.length > 0) { capitalCityData.forEach(city => { const capitalName = city.CapitalName; const capitalLatitude = city.CapitalLatitude; const capitalLongitude = city.CapitalLongitude; map.flyTo([capitalLatitude, capitalLongitude], 5); // Create a marker for each capital city const marker = L.marker([capitalLatitude, capitalLongitude]) .addTo(map) .bindPopup(capitalName); }) } }) .catch(error => { console.error('problems loading capital city data', error) }); }
问题原因及修复
核心原因
问题出在以下两行代码:
var selectedCountry = dropdown.options[dropdown.selectedIndex]; $('#txtWiki').html(selectedCountry)
dropdown.options[dropdown.selectedIndex]获取的是**<option> DOM元素对象**,而非选项的文本内容。当你把这个DOM元素直接传入html()方法时,jQuery会将该元素从原下拉菜单中移除,再插入到#txtWiki元素内——这就导致下拉菜单里的选中选项被"移动"走,视觉上表现为消失。
同时,维基链接的生成也会因为用了DOM对象而出现异常,URL会变成包含DOM对象toString结果的错误地址。
修复方案
只需要修改代码,获取选项的文本内容而非DOM元素即可:
- 修改选中值的获取方式:
// 原生JS方式 var selectedCountry = dropdown.options[dropdown.selectedIndex].text; // 或者jQuery方式 var selectedCountry = $('#countries option:selected').text(); - 之后再执行
$('#txtWiki').html(selectedCountry)和$('#txtWiki').attr('href', 'https://en.wikipedia.org/wiki/' + selectedCountry)时,只是把文本内容插入元素,不会移动原下拉菜单的<option>元素,下拉菜单的选项就不会消失,维基链接也能正常生成。
内容的提问来源于stack exchange,提问作者lizmosis
相关产品推荐
相关产品推荐

