我应该如何在之前(在不同的函数中)返回一个元素,并在一个新函数中修改它?

时间:2018-04-25 23:54:34

标签: javascript html css

如何参考我创建的特定短划线,并添加一个    特别给他们的信。阅读评论和代码以获得更好的结果    上下文。在此先感谢您的帮助!!

<!Doctype html>
<html lang="en">
<head>
<style>
ul {
display: inline;
list-style-type: none;
}

.boxes {
font-size:1.6em;
text-align:center;
width: 10px;
border-bottom: 3px solid black;
margin: 5px;
padding: 10px;
display: inline;
}
.hidden {
visibility: hidden;
}
.visible {
visibility: visible;
}

</style>
</head>
<body>
<script>

var possibleWord = ["COW", "BETTER", "HARDER", "JUSTIFY", "CONDEMN", 
"CONTROL", "HELLO", "UNDERSTAND", "LIFE", "INSIGHT","DATE", 
"RIGHTEOUSNESS"];
var hangmanWord = possibleWord[Math.floor(Math.random() * 
possibleWord.length)];
var underlineHelp;
var space;
var guess;
var guesses = [];
var placement;
var underscores = [];
var character = [];
var textNodes = [];
window.onload = function () {
placement = document.getElementById('hold');
underlineHelp = document.createElement('ul');
placement.appendChild(underlineHelp);
for (i = 0; i < hangmanWord.length; i++) {
underscores = document.createElement('li');
underscores.setAttribute('class', 'boxes');
guesses.push(underscores);
underlineHelp.appendChild(underscores);
character = document.createElement('span');
character.appendChild(document.createTextNode(hangmanWord[i]));
character.classList.add('hidden');
underscores.appendChild(character);
}

这是我想稍后提及的区域。

for(x=1;x<=26;x++){
document.getElementById("test").innerHTML = hangmanWord;
var btn = document.createElement("BUTTON");
var myP = document.createElement("br");


var letter = String.fromCharCode(x+64);
var t = document.createTextNode(letter);

btn.appendChild(t);

btn.id = letter;

只需创建按钮。当我在下面说'this.id'时,这很重要。

btn.addEventListener("click", checkLetter);

document.body.appendChild(btn);
//add a line break 'myP' after 3 buttons
if (x%10==0) {
document.body.appendChild(myP);
}
}
}

function checkLetter(){
//this refers to the object that called this function
document.getElementById("p1").innerHTML += this.id;
for (i = 0; i < hangmanWord.length; i++) {
guess = hangmanWord[i];
if (this.id == guess) {
character[i] = hangmanWord[i];
character.appendChild(document.createTextNode(hangmanWord[i]));
character.classList.add('visible');

}
}
}

这是我遇到麻烦的地方。如果我这样做(我在if语句之后编写的代码),字母将被添加到字符串的末尾。我希望在我之前创建的特定破折号上拥有它。我怎么能设法做到这一点?我是否必须做一些叫做“对象传递”的事情。我对js(高中生)相对较新,我热衷于任何见解!再次感谢您的帮助!

</script>

</head>
<body>

<p>Click the button to make a BUTTON element with text.</p>
<div id = "contents">
<div id = "hold"></div>
</div>
<p id ="p1"> Letters picked: </p>
<div id= "picBox"></div>
<div id = "test"></div>



</div>
</body>

1 个答案:

答案 0 :(得分:0)

您可以将猜测词和猜测的字符存储在对象中,只输出替换后的结果。对我来说似乎更容易。

<html>
    <head>
        <script>
            //The hangman object
            var Hangman = {
                wordToGuess: 'RIGHTEOUSNESS', //The word to guess. Just one for my example
                guessedLetters: [] //The guessed characters
            };

            window.onload = function(){
                //Creating the buttons
                for(var tF=document.createDocumentFragment(), x=1; x<=26; x++){
                    var tLetter = String.fromCharCode(x+64),
                        tButton = tF.appendChild(document.createElement("button"));

                    tButton.id = tLetter;
                    tButton.addEventListener("click", checkLetter);
                    tButton.appendChild(document.createTextNode(tLetter));

                    (x%10 === 0) && tF.appendChild(document.createElement('br'))
                };

                document.body.appendChild(tF);
                startTheGame()
            };

            //Starts a game of hangman
            function startTheGame(){
                var tWord = Hangman.wordToGuess,
                    tPlacement = document.getElementById('hold');

                document.getElementById('test').innerHTML = tWord;

                //Resetting the guesses
                Hangman.guessedLetters = [];

                //Creating dashes for all letters in our word
                for(var i=0, j=tWord.length; i<j; i++){
                    tPlacement.appendChild(document.createTextNode('_'))
                }
            }

            function checkLetter(){
                var tButton = this,
                    tLetter = tButton.id,
                    tWord = Hangman.wordToGuess,
                    tPlacement = document.getElementById('hold');

                //Make a guess
                document.getElementById('p1').innerHTML += tLetter;
                (Hangman.guessedLetters.indexOf(tLetter) === -1) && Hangman.guessedLetters.push(tLetter.toLowerCase());

                //Clear the current word
                while(tPlacement.firstChild) tPlacement.removeChild(tPlacement.firstChild);

                //Now we reverse replace the hangman word by the guessed characters
                for(var i=0, j=tWord.length; i<j; i++){
                    tPlacement.appendChild(document.createTextNode(
                        (Hangman.guessedLetters.indexOf(tWord[i].toLowerCase()) === -1) ? '_' : tWord[i]
                    ))                  
                }
            }
        </script>
    </head>

    <body>
        <p>Click the button to make a BUTTON element with text.</p>
        <div id = 'contents'>
            <div id = 'hold'></div>
        </div>
        <p id = 'p1'> Letters picked: </p>
        <div id= "picBox"></div>
        <div id = "test"></div>

        <!-- This one seems to be too much
            </div>
        -->
    </body>
</html>

https://jsfiddle.net/zk0uhetz/

更新

制作了一个带有属性对象处理的版本,将实际的hangman逻辑与接口分开。

<html>
    <head>
        <style>
            button{
                margin: 1px;
                min-width: 30px
            }

            button[disabled]{
                background: #777;
                color: #fff
            }
        </style>

        <script>
            //Handles the hangman game itself
            ;(function(ns){
                'use strict';

                var _listOfWord = ['COW', 'BETTER', 'HARDER', 'JUSTIFY', 'CONDEMN', 'CONTROL', 'HELLO', 'UNDERSTAND', 'LIFE', 'INSIGHT','DATE', 'RIGHTEOUSNESS'],
                    _wordToGuess = null, //The word to guess. Just one for my example
                    _guessedLetters = [] //The guessed characters

                ns.Hangman = {
                    //Returns the current obstructed word
                    getCurrentObstructedWord: function(){
                        var tWord = []; //The current state of the game

                        if(_wordToGuess){
                            //Now we reverse replace the hangman word by the guessed characters
                            for(var i=0, j=_wordToGuess.length; i<j; i++){
                                tWord.push(
                                    (_guessedLetters.indexOf(_wordToGuess[i].toLowerCase()) === -1) ? '_' : _wordToGuess[i]
                                )
                            }
                        };

                        return tWord
                    },

                    //Make a guess at the current game
                    Guess: function(letter){
                        //Add the guess to the list of guesses, unless already guessed
                        (_guessedLetters.indexOf(letter) === -1) && _guessedLetters.push(letter.toLowerCase());

                        return this.getCurrentObstructedWord()
                    },

                    isComplete: function(){
                        return !!(this.getCurrentObstructedWord().indexOf('_') === -1)
                    },

                    //Starts a new game
                    Start: function(){
                        _guessedLetters = []; //Resetting the guesses
                        _wordToGuess = _listOfWord[Math.floor(Math.random() * _listOfWord.length)];

                        return _wordToGuess
                    }
                }
            }(window._ = window._ || {}));

            //Creates the buttons for hangman
            function createButtons(){
                var tContainer = document.querySelector('#buttons');
                while(tContainer.firstChild) tContainer.removeChild(tContainer.firstChild);

                //Creating the buttons
                for(var tF=document.createDocumentFragment(), x=1; x<=26; x++){
                    var tLetter = String.fromCharCode(x+64),
                        tButton = tF.appendChild(document.createElement('button'));

                    tButton.id = tLetter;
                    tButton.addEventListener('click', makeAGuess);
                    tButton.appendChild(document.createTextNode(tLetter));

                    (x%10 === 0) && tF.appendChild(document.createElement('br'))
                };

                tContainer.appendChild(tF)
            };

            //Makes a guess
            function makeAGuess(){
                var tButton = this,
                    tLetter = tButton.id;

                //Disable the button
                tButton.setAttribute('disabled', 'disabled');

                //Make a guess
                var tElement = document.getElementById('hold');
                tElement.textContent = _.Hangman.Guess(tLetter).join('');

                //Check if finished
                if(_.Hangman.isComplete()){
                    tElement.style.color = 'limegreen'
                }
            };

            //Starts a new game of hangman
            function Reset(){
                createButtons(); //Recreated the buttons
                _.Hangman.Start(); //Starting a game of hangman

                var tElement = document.getElementById('hold');
                tElement.textContent = _.Hangman.getCurrentObstructedWord().join('');
                tElement.style.color = ''
            };

            window.onload = function(){
                Reset()
            };
        </script>
    </head>

    <body>
        <div id = 'hold'></div>
        <p id = 'p1'>Make a guess:</p>
        <div id = 'buttons'></div>
        <br /><br />
        <button onclick = 'Reset()'>Start a new game</button>
    </body>
</html>

https://jsfiddle.net/mm6pLfze/