[英]Javascript - iterate to the next element based on condition
我被困在如何根据函数中的条件迭代到下一个元素。 一旦用户突出显示了正确的单词并显示了已完成的消息,它就应该继续前进到从数组onA取得的下一个定义/单词。 在底部,我放置了一个伪代码,因为我不知道如何从该函数访问条件语句的结果。
var onA = [
{t: "grooming", d: "an activity when someone builds an emotional connection with a child to gain their trust for the purposes of sexual abuse or exploitation."},
{t: "cyberbullying", d: "an activity that involves the use of ICT, particularly mobile phones and the internet, deliberately to upset, threaten and intimidate someone else."}
];
function getSelectionHandler(index) {
return function clickHandler() {
var txt = '';
var feedback = document.querySelector("#onA .feedback");
if (window.getSelection) {
txt = window.getSelection().toString();
} else if (document.selection) {
txt = document.selection.createRange().text;
}
// Display the selected text
document.querySelector("#onA .word").innerHTML = txt;
// Change the type of bootstrap alert depending on success
function feed(oldClass, newClass, message) {
feedback.classList.remove(oldClass);
feedback.classList.add(newClass);
feedback.innerHTML = message.bold();
}
// Check if the selected word is correct
if (txt === onA[index].t) {
feed("alert-warning", "alert-success", "Well done!");
} else {
feed("alert-success", "alert-warning", "Try again!");
}
};
}
var i = 0
while (i<onA.length) {
document.getElementById("onA").onclick = getSelectionHandler(i);
document.querySelector("#onA .def").innerHTML += onA[i].d;
if condition in the if statement above is true:
i++
}
全局变量可用于记录当前状态。 我只是写它的手,如果需要,您必须对其进行调试。
function getSelectionHandler(){
var txt = '';
var feedback = document.querySelector("#onA .feedback");
if (window.getSelection) {
txt = window.getSelection().toString();
} else if (document.selection) {
txt = document.selection.createRange().text;
}
// Display the selected text
document.querySelector("#onA .word").innerHTML = txt;
// Change the type of bootstrap alert depending on success
function feed(oldClass, newClass, message) {
feedback.classList.remove(oldClass);
feedback.classList.add(newClass);
feedback.innerHTML = message.bold();
}
// Check if the selected word is correct
if (txt === onA[index].t) {
feed("alert-warning", "alert-success", "Well done!");
index++; //increase before showing next or checking end
if (checkEnded()){
//all end, show end msg
feed("alert-warning", "alert-success", "Finish!");
}else {
//show next
showNext();
}
} else {
feed("alert-success", "alert-warning", "Try again!");
}
}
function checkEnded(){
return index >= onA.length;
}
function showNext(){
document.querySelector("#onA .def").innerHTML += onA[index].d; //display next item
}
var index = 0; //global index for selecting from the array
document.getElementById("onA").onclick = function(){getSelectionHandler();} //register hanlder onc time only
document.querySelector("#onA .def").innerHTML += onA[index].d; //display first item
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.