3 回答
TA贡献1790条经验 获得超9个赞
您必须filter
在循环外使用并获取source[i]
选项中的值。
也只是.html()
用来清空。select
onchange
给你 => 工作演示:https ://jsfiddle.net/usmanmunir/u38hrox1/11/
只需运行代码片段即可查看它的作用。
let types = [
{
"id": 1,
"media": "TV",
"source": "wkbw"
},
{
"id": 2,
"media": "TV",
"source": "wffo"
},
{
"id": 3,
"media": "TV",
"source": "wtrw"
},
{
"id": 8,
"media": "Radio",
"source": "wrqa"
},
{
"id": 9,
"media": "Radio",
"source": "wuqa"
},
{
"id": 10,
"media": "Radio",
"source": "wzzt"
}
]
$("#type").change(function() {
$("#results").html('')
var selected = $("#type").val();
var source = types.filter(types => types.media === selected).map(d => d.source);
for (var i = 0; i < source.length; i++) {
$("#results").append("<option value='" + source[i] + "'>" + source[i] + "</option>");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="type">
<option value="TV">TV</option>
<option value="Radio">Radio</option>
</select>
<hr>
<select id="results">..results</select>
TA贡献1993条经验 获得超5个赞
只需使用这样的简单 if 语句重写您的代码:
let types = [
{
"id": 1,
"media": "TV",
"source": "wkbw"
},
{
"id": 2,
"media": "TV",
"source": "wffo"
},
{
"id": 3,
"media": "TV",
"source": "wtrw"
},
{
"id": 8,
"media": "Radio",
"source": "wrqa"
},
{
"id": 9,
"media": "Radio",
"source": "wuqa"
},
{
"id": 10,
"media": "Radio",
"source": "wzzt"
}
]
$("#type").change(function() {
$("#results").empty();
selected = $("#type").val();
for (var i = 0; i < types.length; i++) {
if(types[i].media === selected){
$("#results").append("<option value='" + types[i].source +
"'>" + types[i].source + "</option>");
}
}
});
TA贡献1808条经验 获得超4个赞
请看下面的解决方案
let types = [
{
id: 1,
media: "TV",
source: "wkbw",
},
{
id: 2,
media: "TV",
source: "wffo",
},
{
id: 3,
media: "TV",
source: "wtrw",
},
{
id: 8,
media: "Radio",
source: "wrqa",
},
{
id: 9,
media: "Radio",
source: "wuqa",
},
{
id: 10,
media: "Radio",
source: "wzzt",
},
];
const type = document.querySelector("#type");
const result = document.querySelector("#result");
type.addEventListener("change", changeHandler);
function changeHandler(event) {
const output = types
.filter((type) => type.media === event.target.value)
.map((type) => `<option value="${type.source}">${type.source}</option>`)
.join("");
result.innerHTML = output;
}
<select name="type" id="type">
<option value="" disabled selected>Select value</option>
<option value="TV">TV</option>
<option value="Radio">Radio</option>
</select>
<select name="result" id="result"></select>
<script src="app.js"></script>
添加回答
举报