HTML的option 的ID 为problem_category动态加载problem_categories.json数据
时间: 2023-05-26 10:02:00 浏览: 54
可以使用JavaScript来实现这个功能。
首先,在HTML中定义一个select元素,并为其添加一个id属性,如下所示:
```html
<select id="problem_category"></select>
```
然后,在JavaScript中使用XMLHttpRequest对象获取problem_categories.json文件中的数据,并将其解析为一个JavaScript对象。接着,遍历该对象的属性,将每个属性的值添加为一个option元素的value和text属性。最后,将这些option元素添加到select元素中。
完整的代码如下所示:
```html
<select id="problem_category"></select>
<script>
const selectElement = document.getElementById('problem_category');
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
const problemCategories = JSON.parse(xhr.responseText);
for (const category in problemCategories) {
const option = document.createElement('option');
option.value = category;
option.text = problemCategories[category];
selectElement.add(option);
}
}
};
xhr.open('GET', 'problem_categories.json');
xhr.send();
</script>
```
注意:为了在本地测试时避免跨域问题,应该将problem_categories.json文件放在与HTML文件同一目录下。如果部署到服务器上,应该将该文件放在一个可以访问的静态资源目录下。