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

如何将API标识值分配给HTML <option>的value属性?

解决方案

1. 修改HTML中<option>的value属性

直接把每个平台选项的value替换成RAWG API对应的平台ID即可——比如你提到的Xbox Series X/S对应187,PlayStation 5对应186,PlayStation 4对应18(这些ID可通过RAWG官方平台列表确认)。修改后的HTML代码如下:

<select class="form-select form-select-lg mb-3 btn btn-secondary btn-lg" id="platform-drop" aria-label=".form-select-lg example">
    <option selected disabled value="">Platforms:</option>
    <option class="dropdown-item" value="186">Playstation 5</option>
    <option class="dropdown-item" value="18">Playstation 4</option>
    <option class="dropdown-item" value="187">XBOX Series X/S</option>
</select>

额外给默认选项加上disabled和value="",防止用户提交未选择的无效状态。

2. 优化JavaScript请求逻辑

你的现有JS代码已经能正确获取选中项的value,可以加个简单校验避免无效请求,同时优化代码可读性:

var platformBtn = $('#platform-drop');
var genreBtn = $('#genre-drop');
var submitBtn = $('#submit-btn');

submitBtn.on('click', function(event){
    event.preventDefault();

    var platformSelection = $("#platform-drop option:selected").val();
    var genreSelection = $('#genre-drop option:selected').val();

    // 校验是否选择了有效选项
    if (!platformSelection || !genreSelection) {
        alert('请选择平台和分类');
        return;
    }

    console.log('选中平台ID:', platformSelection);
    console.log('选中分类ID:', genreSelection);
    
    // 用模板字符串拼接URL,更清晰
    var gamesUrl = `https://api.rawg.io/api/games?genres=${genreSelection}&platforms=${platformSelection}&key=0da6d52b21ec4d8fac88f4f4ceafe806`;

    fetch(gamesUrl)
    .then(function (response) {
        if (response.ok) {
            return response.json();
        }
        throw new Error('请求失败');
    })
    .then(function (data) {
        console.log(data.results);
    })
    .catch(function(error) {
        console.error('请求出错:', error);
    })
})

优化点说明:

  • 用模板字符串替代加号拼接URL,可读性更强
  • 增加选项校验,避免用户未选择就发起请求
  • 补充请求失败的错误捕获逻辑

核心逻辑说明

RAWG API的platforms和genres参数只接受对应数字ID,所以直接把<option>的value设为数字ID是最直接的方案,不需要额外做字符串到ID的映射转换。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 10:21:58