我正在嘗試使用 jQuery & Arrays 構建一個重復出現的邏輯,但遇到了讓代碼重新運行的問題。一旦用戶單擊“下一個按鈕”,我希望代碼讀取矩陣中的下一個陣列。目前,邏輯沒有超過第一個陣列,但我不知道為什么!任何幫助表示贊賞。
<body>
<div id="wordZone"></div>
<ul id="choices">
<li></li>
<li></li>
<li></li>
</ul>
<a href="#" id="next" class="translate">Next Word</a>
<div class="win">
You've Won!
</div>
<div class="lose">
You've Lost!
</div>
</body>
let score = 0;
const dict = {
officeSpeak: ["Hi there!", "Regards", "Per my last email"],
counter: 0,
};
const matrix = [
["Hi there!", "Sup dude", "Salutations"],
["Regards", "Hasta luego", "Byebye"],
["Per my last email","oopsie!","some other option here, you're writing this game"],
];
const wordZone = $("#wordZone");
const choiceButtons = $("#choices li");
function buildOptions() {
let turnChoices = matrix[0];
//hide next word button - DONE
$("#next").hide();
for (let i = 0, ii = turnChoices.length; i < ii; i ) {
let choiceWord = turnChoices[i];
let choiceButton = $(choiceButtons[i]);
let btnClass = "incorrect";
choiceButton.text(choiceWord);
if (dict.officeSpeak.indexOf(choiceWord) != -1) {
btnClass = "correct";
}
choiceButton.addClass(btnClass);
}
}
buildOptions();
function onClickWord(e) {
console.log($(this));
$("#choices li").addClass("active");
$(".correct").css("color", "green");
$(".incorrect").css("color", "red");
if ($(this).hasClass("correct")) {
score ;
console.log(score);
}
$("#next").show();
let turnChoices = matrix[ 1];
}
$("#choices li").click(onClickWord);
$("#next").click(buildOptions);
function finalScore() {
$("#wordZone").show(score);
if (finalScore >= 2) {
$("#wordZone").addClass("win");
$("#win").show();
} else {
$("#wordZone").addClass("lose");
$("#lose").show();
}
}
finalScore();
//final score - HELP
我嘗試創建一個 for 回圈,其中矩陣計數器應在每次運行程式時遞增 1,期望代碼隨后會移動到陣列的第二行。
uj5u.com熱心網友回復:
花了一段時間才找到跑步的方法。這是我的建議:
第一:創建一個全域范圍的變數
let matrixcounter = 0;
第二:向函式添加一個引數buildOptions并將其傳遞給您的陣列matrix[]:
function buildOptions(wordCounter) {
let turnChoices = matrix[wordCounter];
...
}
最后一個更改需要另一個重要更改,基于How can I pass arguments to event handlers in jQuery? :
所以替換$("#next").click(buildOptions);為
$("#next").click(function() {
matrixcounter ; //means matrixcounter = matrixcounter 1;
buildOptions(matrixcounter);
});
一個運行示例:https ://jsfiddle.net/reporter/rtqgveuo/1/
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/454304.html
