https://jsfiddle.net/mf553ccL/
我想选择选择类型,然后过滤电影列表,以便只显示具有该类型的电影。
<body>
<div id="select-parent">
<select id="selection">
</select>
</div>
<div id="output"></div>
<script src="js/script.js"></script>
</body>
我尝试过使用:
if (selection.value == data.movie.categories) {
classList.add('hidden');
}
但我收到了data.movie.categories。
TypeError:数据未定义
这是我的Javascript,因此您可以看到代码:
window.addEventListener("load", setup);
function setup() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'data/data.json', true);
xhr.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
var data = JSON.parse(this.responseText);
var output = '';
var genre = '<option> ' + "-- Select Genre --" + ' </option>';
for (var i = 0; i < data.movies.length && data.categories.length; i++) {
if (i < data.categories.length) {
genre += '<option> ' + data.categories[i] + ' </option>';
}
output += '<ul>' +
'<li> Title: ' + data.movies[i].title + '</li>' +
'<li> Category: ' + data.movies[i].categories + '</li>' +
'</ul>';
}
document.getElementById('output').innerHTML = output;
document.getElementById('selection').innerHTML = genre;
}
console.log(data.movies.categories);
}
xhr.onerror = function() {
console.log("req")
}
xhr.send();
}
我的数据对象位于JSON文件中:
{
"movies": [{
"title": "Mad Max",
"categories": "action"
}, {
"title": "Willow",
"categories": "action,fantasy"
}, {
"title": "Alien",
"categories": "action,sci-fi"
}, {
"title": "Silence of the lambs",
"categories": "thriller"
}, {
"title": "The Ring",
"categories": "horror"
}, {
"title": "Gone with the wind",
"categories": "drama"
}, {
"title": "Lion King",
"categories": "animation, family"
}, {
"title": "Jumanji",
"categories": "action,fantasy, family"
}, {
"title": "Heat",
"categories": "action,thriller"
}, {
"title": "Blade runner",
"categories": "action,sci-fi"
}],
"categories": ["action", "sci-fi", "drama", "thriller", "horror", "fantasy", "family", "animation"]
}