gpt4 book ai didi

javascript - 我将如何结合这两个相似的功能?

转载 作者:行者123 更新时间:2023-11-29 16:10:56 25 4
gpt4 key购买 nike

我创建了两个运行一组类似 IF 语句的函数,一个显示游戏的成本,另一个显示它的名称。我使用“onclick”在我的表单中显示这两个值。这一切都有效,但会膨胀。有没有办法结合这两个功能来缩短脚本?

        function GameTitle() {
var textboxValue = document.getElementById("game_id").value;
var message;
if (textboxValue == 1) {
message = "Fantasy World";
} else if (textboxValue == 2) {
message = "Sir Wags A Lot";
} else if (textboxValue == 3) {
message = "Take a Path";
} else if (textboxValue == 4) {
message = "River Clean Up";
} else if (textboxValue == 5) {
message = "PinBall";
} else if (textboxValue == 6) {
message = "Ghost girl";
} else if (textboxValue == 7) {
message = "Dress Up";
} else if (textboxValue == 8) {
message = "Where is my hat?";
} else {
message = "Invalid ID";
}
document.getElementById("game_title").value = message;
}

//Display price of Game
function Cost() {
var textboxValue = document.getElementById("game_id").value;
var cost;
if (textboxValue == 1) {
cost = "0.99";
} else if (textboxValue == 2) {
cost = "0.99";
} else if (textboxValue == 3) {
cost = "1.99";
} else if (textboxValue == 4) {
cost = "1.99";
} else if (textboxValue == 5) {
cost = "3.99";
} else if (textboxValue == 6) {
cost = "3.99";
} else if (textboxValue == 7) {
cost = "1.99";
} else if (textboxValue == 8) {
cost = "1.99";
} else {
cost = "Invalid ID";
}
document.getElementById("cost").value = cost;
}

最佳答案

你应该为此使用一个对象数组

var games = [
{
message : "Fantasy World",
cost : 0.99
},
{
message : "Sir Wags A Lot",
cost : 0.99
},
{
message : "Take a Path",
cost : 1.99
},
{
message : "River Clean Up",
cost : 1.99
},
{
message : "PinBall",
cost : 3.99
},
{
message : "Ghost girl",
cost : 3.99
},
{
message : "Dress Up",
cost : 1.99
},
{
message : "Where is my hat?",
cost : 1.99
}
];

然后在您的函数中您可以接受和 id,引用其在数组中的索引(基于 0 偏移 1)并使用该对象。

function Display(){
var textboxValue = parseInt(document.getElementById("game_id").value,10);
document.getElementById("game_title").value =
textboxValue-1 < games.length ? games[textboxValue-1].message : "Invalid ID";
document.getElementById("cost").value =
textboxValue-1 < games.length ? games[textboxValue-1].cost : "Invalid ID";
}

关于javascript - 我将如何结合这两个相似的功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28223622/

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