如何从用户那里获取值并在Javascript中使用它

时间:2018-08-29 19:18:16

标签: javascript

我正在尝试制作问答游戏,并希望允许用户选择游戏难度。我有一个JSON列表,其中包含问题。

var easy = '[{"eser":"Question1","yazar":"Answer1"},{"eser":"Question2","yazar":"Answer2"}]';
var hard = '[{"eser":"Question3","yazar":"Answer3"},{"eser":"Question4","yazar":"Answer4"}]';

我解析如下

difficulty = JSON.parse(easy);
var count = Object.keys(difficulty).length;

游戏打开时,会显示一个弹出窗口,要求用户选择难度。基本上,当用户单击“困难”时,我想捕获它并将上面的代码更改为difficulty = JSON.parse(hard);

HTML代码在这里

<div class="button_easy">Easy</div>
<div class="button_hard">Hard</div>

谢谢

2 个答案:

答案 0 :(得分:1)

请勿使用单独的变量,而应使用键与其所选择元素中的某项相对应的对象。

const questions = {
    easy: [{"eser":"Question1","yazar":"Answer1"},{"eser":"Question2","yazar":"Answer2"}],
    hard: [{"eser":"Question3","yazar":"Answer3"},{"eser":"Question4","yazar":"Answer4"}]
};

HTML可以像这样:

<div class="difficulty" data-level="easy">Easy</div>
<div class="difficulty" data-level="hard">Hard</div>

JS是:

let chosen_questions;
document.querySelector(".difficulty").forEach(b => b.addEventListener("click", function() {
    let level = this.dataset.level;
    chosen_questions = questions[level];
}));

答案 1 :(得分:-2)

您可以使用eval函数来完成此操作(如果没有名为user_choice表示的字符串的变量,此处将省略错误处理):

 var difficulty = JSON.parse(eval(user_choice))

但是我认为将这两个列表放在这样的字典中可能会更好:

var difficulty_dic = {
  'easy': easy,
  'hard': hard
}

然后您可以执行以下操作:

var difficulty = JSON.parse(difficulty_dic[user_choice])