You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用jQuery正确获取表单中被选中的<option>元素值?

如何正确获取
  • 内class为country的select元素的选中值
  • 问题根源

    你当前的代码存在三个关键问题:

    1. 事件绑定错误:给<option>绑定click事件不是监听选择变化的正确方式——用户可能通过键盘切换选项,此时click事件不会触发,应该监听<select>的change事件。
    2. 语法与拼写错误:$('.optionResutl').$(this)是无效的jQuery语法,而且optionResutl是拼写错误(正确应为optionResult)。
    3. option属性缺失:创建<option>时未设置value属性,导致val()的行为依赖浏览器默认逻辑,容易出现不一致。

    修正方案

    1. 修复option创建代码

    创建选项时显式设置value属性,确保val()能准确获取对应值:

    for (let i = 0; i < result.length; i++) {
      // 显式设置value属性,与text一致(也可根据需求设置其他值,比如国家代码)
      let option = $("<option></option>")
        .val(result[i].name)
        .text(result[i].name)
        .addClass("optionResult");
      $(".country").append(option);
    }
    

    2. 绑定select的change事件替代option的click事件

    直接监听.country的change事件,在回调中获取选中值:

    $('.country').on('change', function() {
      // 获取选中项的value(如果option的value和text一致,也可用text())
      let selectedCountry = $(this).val();
      // 或者用以下方式获取选中项的文本,更明确
      // let selectedCountry = $(this).find('option:selected').text();
      
      console.log(selectedCountry, 'selected country var');
    
      // 后续的border数据请求逻辑保持不变
      $.ajax({
        url: './countryBorders.geo.json',
        type: 'GET',
        dataType: 'json',
        success: function(borders) {
          let input = [];
          borders.features.forEach((border) => {
            console.log('name in borders', border.properties.name);
            console.log('name in selectors', selectedCountry);
            
            // 匹配逻辑:判断国家名称是否一致
            if (border.properties.name === selectedCountry) {
              input.push(border);
            }
          })
    
          // 地图渲染逻辑
          L.geoJSON(input, {
            style: function(feature) {
              return { color: feature.properties.color || '#ff0000' }; // 设置默认颜色避免undefined
            }
          }).bindPopup(function(layer) {
            return layer.feature.properties.description || '无描述信息';
          }).addTo(map);
        },
        error: function(jqXHR, textStatus, errorThrown) {
          console.log(JSON.stringify(errorThrown));
        }
      })
    })
    

    完整修正后的代码

    把上述修正部分替换原代码对应的逻辑,整体代码如下:

    $.ajax({
      url: "../project1/php/countries.php",
      type: 'GET',
      dataType: 'json',
      success: function(res) {
        if (res) {
          // map这里可以简化,直接用res即可,不需要重新赋值
          let result = res.map((country) => country);
    
          // 创建国家选项
          for (let i = 0; i < result.length; i++) {
            let option = $("<option></option>")
              .val(result[i].name)
              .text(result[i].name)
              .addClass("optionResult");
            $(".country").append(option);
          }
    
          // 监听select的change事件
          $('.country').on('change', function() {
            let selectedCountry = $(this).val();
            console.log(selectedCountry, 'selected country var');
    
            $.ajax({
              url: './countryBorders.geo.json',
              type: 'GET',
              dataType: 'json',
              success: function(borders) {
                console.log(borders);
                let input = [];
                borders.features.forEach((border) => {
                  console.log('name in borders', border.properties.name);
                  console.log('name in selectors', selectedCountry);
    
                  if (border.properties.name === selectedCountry) {
                    input.push(border);
                  }
                })
    
                L.geoJSON(input, {
                  style: function(feature) {
                    return { color: feature.properties.color || '#ff0000' };
                  }
                }).bindPopup(function(layer) {
                  return layer.feature.properties.description || '无描述信息';
                }).addTo(map);
              },
              error: function(jqXHR, textStatus, errorThrown) {
                console.log(JSON.stringify(errorThrown));
              }
            })
          })
        }
      },
      error: function(jqXHR, textStatus, errorThrown) {
        console.log(JSON.stringify(errorThrown));
      }
    });
    

    额外说明

    • 如果你的国家数据里有唯一标识(比如国家代码),建议把option的value设置为该标识,而不是名称,这样匹配时更准确(避免名称拼写不一致的问题)。
    • 若需要默认选中某个选项,可以在创建完所有option后,调用$('.country').val('默认国家名称')来设置。

    内容的提问来源于stack exchange,提问作者Kyle Ghilotti

    相关产品推荐
    方舟 Agent Plan

    超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

    最近更新时间:2026.07.27 20:00:00