JS清除下一个输出的文本

时间:2015-05-15 12:37:35

标签: javascript

下面的代码混淆了一个短语,然后要求用户重新排列成正确的逻辑顺序,当输入正确的短语时,代码输出'正确答案'然后输出第二个问题,但是输出''右边回答'还在显示。如何在下一个问题中清除它?

Thx Pav

var currentQuestion = 0;

var words = 
        [
    ['how', 'are', 'you', 'today?'],
    ['what', 'would', 'you', 'like', 'for', 'breakfast?'],
    ['what', 'would', 'you', 'like', 'for', 'tea?']
];

var correctInput = [
    ['how are you today?'],
    ['what would you like for breakfast?'],
    ['what would you like for tea?']
];


function showQuestion(i) {
    if(i < words.length) {
        document.myForm.textinput.value = '';
        newWords = words[i].slice(0);
        shuffle(newWords);
        var el = document.getElementById('phrase');
        el.textContent = newWords.join(' ');
    }
}

function setup() {
    showQuestion(currentQuestion);
    var form = document.getElementById('myform');
    form.addEventListener('submit', checkAnswer, false);
}

function checkAnswer(e){
    e.preventDefault();
    var elMsg = document.getElementById('feedback');
    if (document.myForm.textinput.value == correctInput[currentQuestion]) {
            elMsg.textContent= "right answer";
            currentQuestion++;
            showQuestion(currentQuestion);
    } else {
        elMsg.textContent= "wrong answer";
    } 
}

function shuffle(newWords) {
    var counter = newWords.length, temp, index;
    while (counter > 0) {
        index = Math.floor(Math.random() * counter);
        counter--;
        temp = newWords[counter];
        newWords[counter] = newWords[index];
        newWords[index] = temp;}
    return newWords;}

setup();
<!DOCTYPE html> 
<html> 
<head> 
    <title>My Page</title>  
</head> 
<body>  
    <form  name="myForm" id ="myform">
        <div id ="phrase"></div>    
        <input type = "text" id = "textinput"> 
        <button id="myBtn">Click here</button>
        <div id ="feedback"></div>
    </form>
    <script src = "phraseScrambler.js"></script>  
</body>
</html>

3 个答案:

答案 0 :(得分:0)

添加:

document.getElementById('feedback').text = '';

在您要清除“正确答案”的位置。

您可以将此绑定到文本框上的onKeyUp事件侦听器。这样,当用户开始输入下一个答案时,它将清除“正确答案”。

答案 1 :(得分:0)

您可以将事件侦听器附加到输入字段,如此

<input onfocus='document.getElementById("feedback").innerHTML = "";'>

每次输入被聚焦时,这将清除反馈。

答案 2 :(得分:0)

这将在3秒后隐藏这两条消息。

if (document.myForm.textinput.value == correctInput[currentQuestion]) {
        elMsg.textContent= "right answer";
        currentQuestion++;
        showQuestion(currentQuestion);
} else {
    elMsg.textContent= "wrong answer";
} 
setTimeout((function (elMsg) { return function () {
    elMsg.textContent = '';
}})(elMsg), 3000)