I'm trying to build a reoccurring logic using jQuery & Arrays, but running into issues with getting the code to rerun. I'd like the code to read the next array within the matrix once the user clicks "Next Button." Currently, the logic isn't progressing past the first array, but I'm not sure why! Any help is appreciated.
<body>
<div id="wordZone"></div>
<ul id="choices">
<li></li>
<li></li>
<li></li>
</ul>
<a href="#" id="next" >Next Word</a>
<div >
You've Won!
</div>
<div >
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
I tried creating a for loop where the matrix counter should increment by 1 each time the program is ran, expecting that the code would then move onto the second line of the array.
CodePudding user response:
It tooks a while to find a running way. Here my suggestion:
First: create a variable with global scope
let matrixcounter = 0;
Second: Add an argument to function buildOptions
and pass it to your array matrix[]
:
function buildOptions(wordCounter) {
let turnChoices = matrix[wordCounter];
...
}
This last change needs another important change, based on How can I pass arguments to event handlers in jQuery? :
So replace $("#next").click(buildOptions);
with
$("#next").click(function() {
matrixcounter ; //means matrixcounter = matrixcounter 1;
buildOptions(matrixcounter);
});
A running example: https://jsfiddle.net/reporter/rtqgveuo/1/