尝试使用JavaScript编写按钮功能。我希望函数同时隐藏一些ID元素并显示其他ID元素。到目前为止,这就是我所拥有的。没用我对JavaScript非常陌生,因此我的代码很有可能是垃圾。任何帮助表示赞赏。
function mlbShowTeamsMap() {
document.getElementById("mlbTeamsMap").style.display = "block";
document.getElementById("mlbTeamsList").style.display = "block";
var mlbOther = ["nflTeamsList", "nflTeamsMap", "nhlTeamsList", "nhlTeamsMap", "nbaTeamsList", "nbaTeamsMap"];
mlbOther.forEach(hide);
function hide() {
style.display = "none";
}
}
答案 0 :(得分:0)
您正在使用forEach
来迭代数组mlbOther
。现在forEach
接受一个数组,并具有一个回调函数,该函数将第一个参数作为数组的元素。因此,您的回调函数hide
需要定义一个变量以接受此参数。请在下面找到代码。
更正的语法
function mlbShowTeamsMap() {
document.getElementById("mlbTeamsMap").style.display = "block";
document.getElementById("mlbTeamsList").style.display = "block";
var mlbOther = ["nflTeamsList", "nflTeamsMap", "nhlTeamsList", "nhlTeamsMap", "nbaTeamsList", "nbaTeamsMap"];
mlbOther.forEach(hide);
function hide(id) {
document.getElementById(id).style.display = "none";
}
}
使用箭头功能的替代语法
function mlbShowTeamsMap() {
document.getElementById("mlbTeamsMap").style.display = "block";
document.getElementById("mlbTeamsList").style.display = "block";
var mlbOther = ["nflTeamsList", "nflTeamsMap", "nhlTeamsList", "nhlTeamsMap", "nbaTeamsList", "nbaTeamsMap"];
mlbOther.forEach(id => {
document.getElementById(id).style.display = "none";
});
}
阅读更多