简体   繁体   中英

Checking characters in string against keypress - Javascript

I'm building a hangman game in javascript and I've hit a bump. I'm trying to compare a keyboard press with all characters from string 'theword'. With this, I would need the program to change the corresponding dash (array position?) on screen which is in the DOM like this:

    <p id="usedletters">
       <span>_</span>
       <span>_</span> etc...
    </p>

... with the letter that has been pressed if it exists in theword. The program would have to not allow that character to be pressed again. All incorrect characters would be placed and shown elsewhere on the page. I'm not using any libraries.

Any help apreciated.

Thanks.

There is a pseudo class called :nth-child that allows you to select the nth child of a tag. The usage is this usedletters:nth-child(n) to select element n. You do not specify how you are selecting elements but if you recognise that the letter in position m has been pressed you can select it using this method and change its value. If you are using jquery you can use this directly.

If you want to do this in pure javascript try this.

var used = document.getElementById('usedletter');
var letter = span.childNodes[n];
letter.innerHTML = value;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM