如何循环将狗狗API的犬种名称注入<select><option>标签
修正后的代码及实现说明
以下是针对狗狗API的完整修正代码,实现了犬种选项填充及信息展示功能:
HTML 结构
<label for="dogTypes">选择犬种:</label> <select id="dogTypes"> <option value="">请选择一个犬种...</option> </select> <button>查看犬种信息</button> <div id="breedInfo"> <h2 id="name"></h2> <img id="breedImage" src="" alt="犬种图片" style="max-width: 400px;"> <h3 id="temperament"></h3> <h4 id="lifespan"></h4> </div>
JavaScript 代码
const api_key = '你的API密钥'; // 替换为你从狗狗API获取的密钥 // 页面加载时填充所有犬种选项 document.addEventListener('DOMContentLoaded', populateBreeds); function populateBreeds() { const url = 'https://api.thedogapi.com/v1/breeds'; fetch(url, { headers: { 'x-api-key': api_key } }) .then(res => res.json()) .then(breeds => { const selectElement = document.querySelector('#dogTypes'); // 循环遍历所有犬种,创建<option>元素并添加到下拉框 breeds.forEach(breed => { const option = document.createElement('option'); option.value = breed.id; // 使用犬种ID作为选项值(唯一标识) option.textContent = breed.name; // 显示犬种名称 selectElement.appendChild(option); }); }) .catch(err => console.error('获取犬种列表失败:', err)); } // 点击按钮获取并展示选中犬种的信息 document.querySelector('button').addEventListener('click', getFetch); function getFetch() { const selectedBreedId = document.querySelector('#dogTypes').value; // 检查是否已选择犬种 if (!selectedBreedId) { alert('请先选择一个犬种!'); return; } const url = `https://api.thedogapi.com/v1/images/search?breed_ids=${selectedBreedId}`; fetch(url, { headers: { 'x-api-key': api_key } }) .then(res => res.json()) .then(data => { if (data.length === 0) { alert('未找到该犬种的图片'); return; } const breedDetails = data[0].breeds[0]; // 更新页面上的犬种信息 document.querySelector('#name').textContent = breedDetails.name; document.querySelector('#breedImage').src = data[0].url; document.querySelector('#temperament').textContent = `性格: ${breedDetails.temperament}`; document.querySelector('#lifespan').textContent = `寿命: ${breedDetails.life_span}`; }) .catch(err => console.error('获取犬种信息失败:', err)); }
关键修正与改进点
- 替换API端点: 将原猫API的URL替换为狗狗API的官方端点,包括获取所有犬种的
/v1/breeds和获取犬种图片的/v1/images/search。 - 填充下拉选项: 新增
populateBreeds函数,在页面加载时自动获取所有犬种,通过循环创建<option>元素并添加到下拉框中。 - API密钥验证: 在请求头中加入
x-api-key字段,符合狗狗API的身份验证要求。 - 错误处理: 添加了未选择犬种、获取数据失败等场景的提示逻辑。
- 安全内容插入: 使用
textContent替代innerHTML,避免潜在的XSS风险。 - 元素关联修正: 修正了
<label>标签的for属性,使其正确关联到下拉框的ID。
内容的提问来源于stack exchange,提问作者Maolean
相关产品推荐
相关产品推荐

