检查输入的单词是否正确

时间:2018-04-19 09:19:41

标签: javascript html

我正在用空行创作一首诗。必须更改空白并创建javascript以检查输入的单词是否应该是诗中的正确单词。

任何人都知道我做错了什么?

<body>
<pre id="poem">
Social Media
Relax yourself,
As I <span id = "word1" contenteditable>______</span>
through your mind
Scroll down the pages
of your spine
Reading every word 
and thought on
your <span contenteditable>____</span> like a <span contenteditable>____</span>
Stumbled Upon 
you then <span contenteditable>_______</span> onto
your looks--IGuess
I'm <span contenteditable>______</span> into you
You're my one
and only <span contenteditable>________</span>

Will you <span contenteditable>______</span> me?

</pre>
<button onsubmit = "isCorrect()"> submit </button>
<p color = "white" id = "demo"></p>

</body>

使用Javascript:

<script>
function isCorrect(){
    var word = document.getElementById("word1").value;
    if (word == "dig")
    {
        document.getElementById("demo").innerHTML = word;
    }
}
</script>

1 个答案:

答案 0 :(得分:0)

word1span,使用innerHTML代替value。我建议addEventListener代替onsubmit

document.querySelector( "button" ).addEventListener( "click", function(){
   isCorrect();
});
function isCorrect(){
    var word = document.getElementById("word1").innerHTML;
    if (word == "dig")
    {
        document.getElementById("demo").innerHTML = word;
    }
}

同样,您也可以检查其他span的值。我建议将值作为span本身的属性,例如

As I <span id = "word1" data-value="dig" contenteditable>______</span>

并验证与

相同
var allSpans = document.querySelectorAll( span[contenteditable] );
Array.from(allSpans).forEach( s => {
   var dataValue = s.getAttribute( "data-value" );
   if (dataValue == s.innerHTML )
   {
     //code for correct value
   }
})