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

标签 javascript forms if-statement

我创建了两个运行一组类似 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/

相关文章:

javascript - jQuery - 为什么警报动画不起作用?

javascript - ELSE IF using 怎么写? : in javascript

c# - 在程序中实现逻辑时,If else 的更好选择是什么? | C#

javascript - Vue.js:如何在应用程序加载之前显示加载语句而不是白页

javascript - Chip8 仿真器上的碰撞检测

Javascript使用map从一维数组创建二维数组

javascript - 表单的 CSS 网格系统(多列)

javascript - 如何清除 dijit 表单中的验证消息

java - 从 map 调用中删除 if 逻辑

javascript - 拖放(jquery ui-droppable)在 AngularJS 中不起作用