それが繰り返されるとJS機能は、HTMLのテキストの色を変更しません。

オレグGulevskyy:

私はこの質問のタイトルを選択するために苦労したが、私は以下の説明に最善を尽くします。

私は正しく単語入力1により及び場合作られたこのチェッカー、入力1からそのチェックの言葉を持っている - それは緑に色が変わります。それは別の単語に分割入力でそれをしないと、アレイに配置します。

私はしかし見ることは私は反対入力ワードを比較していますというテキストでrepeatitive単語があれば、それは色を変更しないということです。なぜそれが可能でしょうか?私は色を変更する私の機能を見る方法はない、配列にその値を言葉の立場をとり、その後、単純にhtml要素の色を追加します。

let text = document.querySelector('.card-body').innerHTML;
let splitText = text.split(' ');

let userInput = document.querySelector('.form-control');
userInput.addEventListener('input', acceptInput)

let correctWords = [];
let mistakes = 0;
let words = [];


function acceptInput() {
    userInput.onkeydown = function(e){
        if(e.keyCode == 32){
            words = userInput.value.split(' ');        
            console.log(words); 
            console.log(splitText);
            let position = words.length-1;
            compareWordsArrays(position);
        }
    }
}

function compareWordsArrays(position) {
    
    for(i = position; i < words.length; i++) {
        if(words[i] === splitText[i]) {
            console.log(`Correct word detected: ${words[i]}`);
            let wordIndex = words.indexOf(words[i]);
            changeColor(wordIndex);

        } else {
            console.log('Incorrect word;');
            mistakes += 1;
            console.log(mistakes);
            
        }
    }
    
}

function changeColor(pos) {
    splitText[pos]="<font color=green>"+splitText[pos]+"</font>";
    let c = splitText.join(' ');
    document.querySelector('.card-body').innerHTML = c;
}
 <div class="card">
    <div class="card-body">Random text that appears from some generator or some stuff. But it needs to have quite few text, actually.
     </div>
</div>
<input type="text" class="form-control">

私の例では、それは間違いのような第2の単語をカウントされませんが、「一部」は変化していないされていないもされていない私は、私は明らかに十分だ願う「一部」repest文中の二回、第二の単語を単語を見ることができます。

ローランS.:

ただ、変更

if(words[i] === splitText[i]) {
        console.log(`Correct word detected: ${words[i]}`);
        let wordIndex = words.indexOf(words[i]);
        changeColor(wordIndex);

    }

if(words[i] === splitText[i]) {
        console.log(`Correct word detected: ${words[i]}`);
        changeColor(i);

    }

なので:

  • あなたが既に知っているインデックスを探していない点は(ありませんi。この場合には)
  • indexOfは、したがって、あなたのスクリプトは最初の出現のために働いて、最初に出現するインデックスを返します...

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=347736&siteId=1