gpt4 book ai didi

javascript - getElementById 到array 来函数切换

转载 作者:行者123 更新时间:2023-11-28 02:27:41 24 4
gpt4 key购买 nike

我正在尝试根据所选标题更改我的标题和横幅 BG。

function display() {

var gameSelected = ["game_dota2","game_clashroyale","game_csgo","game_fortnite","game_pubg",];
var mmgame = document.getElementById(gameSelected);

switch (mmgame){
case "Dota 2":
var mmgame2 = "Dota 2";
break;
case "Clash Royale":
var mmgame2 = "Clash Royale";
break;
}

这就是如何根据 onclick 事件获取选择了什么游戏的想法。

我是初学者,不确定这是否是处理它的最佳方式,如果您有更好的建议,请告诉我。

现在下一个问题是弄清楚什么是将工作 var 实现到另一个 switch 语句的最佳方法,然后使用 .innerHTML 和 .src 将新标题和新 BG 图像推送到站点顶部

switch (mmgame2){
case "Dota 2":
var element = document.getElementById("wht");
element.innerHTML = mmgame2;
document.getElementById("whbg").src = dota2_bg;
break;
case "Clash Royale":
var element = document.getElementById("wht");
element.innerHTML = mmgame2;
document.getElementById("whbg").src = clashroyale_bg;
break;
case "CS:GO":
var element = document.getElementById("wht");
element.innerHTML = mmgame2;
document.getElementById("whbg").src = csgo_bg;
break;
case "Fortnite":
var element = document.getElementById("wht");
element.innerHTML = mmgame;
document.getElementById("whbg").src = fornite_bg;
break;
case "PUB:G":
var element = document.getElementById("wht");
element.innerHTML = mmgame;
document.getElementById("whbg").src = pubg_bg;
break;
default:
var element = document.getElementById("wht");
element.innerHTML = "Your Game Is Not Ready Now";
break;
}

谢谢!

最佳答案

另一种方法可能是这样的:

var selectedGame = getSelectedGame(); //to be defined

var gamesList = {
"Dota 2": {
title: 'Dota 2',
background: '/path/to/Dota2_bg.png'
},
"Clash Royale": {
title: 'Clash Royale',
background: '/path/to/ClashRoyale_bg.png'
},
// add any more games to here, with any needed attributes
};

var game = gamesList[selectedGame];

element.innerHTML = game.title; //set title to game's title as specified above
document.getElementById("whbg").src = game.background; //set background image

这可能更容易扩展。

关于javascript - getElementById 到array 来函数切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52881315/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com