representing a character at various array in an html table w/JQuery/JavaScript

匿名 (未验证) 提交于 2019-12-03 02:35:01

问题:

I've run into some issue graphically representing some of my data via J Query in my Hangman game- right now I'm working on the last part of my play(space) function to take into account if there is more than one correctly guessed letter in a word & to display all instances of that letter- I've made a function to loop through the array created out of the split word, I'm getting the correct indexes of those letters, I'm just kind of stuck as to how to display these letters at these indexes in my table via J Query correctly & I'm kind of stuck... I've been console.log - ing my data & I'm getting the correct data (the letter and the indexes of that letter in my array), I now just need to figure out how to display these letters in my html table at their correct indexes corresponding to the table (I'm feeling kind of stuck & wondering if this is possible to salvage- I'm sure there must be a way to do it, I just haven't figured it out- I'm not sure if I should be creating a dictionary object to pair the correct letter w/it's indexes in the array to use .each() to loop through to graphically represent in my table or if there's a way to graphically represent it w/the data as is). I'd really appreciate any help.

Here's my code: JS/JQuery:

var wordBank = ["modernism", "situationalist", "sartre", "camus", "hegel", "lacan", "barthes", "baudrillard", "foucault", "debord", "baudrillard"]; var word = []; var wrongGuesses = []; var rightGuesses = []; var images = [gallows, head, body, armL, handL, armR, handR, legL, footL, legR, footR]; var y = 0; var i = 1; $(document).ready(function() {   function randomWord() {     var random = Math.floor(Math.random() * wordBank.length);     var toString = wordBank[random];     console.log(toString);     word = toString.split("");     console.log(word);   }   randomWord();    function wordSpaces() {     for (var i = 0; i < word.length; i++) {       $(".word-spaces > tbody > tr").append('<td data-idx=i>' + word[i] + '</td>')     }   }   wordSpaces();    function play(space) {     //indexOf()==inArray()      var lIndex = jQuery.inArray(space, word);     console.log(lIndex);     if (lIndex == -1) {       wrongGuesses.push(space);       var wrong = wrongGuesses.length;       console.log('wrong ' + wrong);       $('.wrongLetters tbody tr td:nth-of-type(' + wrong + ')').text(space);  //      $(this).css("background-color", "#ff4500").fadeIn(300).delay(800).fadeOut(300);       $(images[i - 1]).hide();       $(images[i]).show();       i++;       $("html").css("background-color", "#ff4500").fadeIn(300).delay(300).fadeOut(300).fadeIn(100);       console.log(word);     } else {        console.log(word + "word");        console.log(space + "space");         function getInstances(word,space) {           var indexes = [], w;           for(w=0; w<word.length;w++ )           if (word[w] === space)           indexes.push(w);           return indexes;         }       console.log(word + "word");        console.log(space + "space");       var indexes = getInstances(word, space);       console.log(indexes);       rightGuesses.push(space);       console.log(rightGuesses);        $(".word-spaces tbody tr td:nth-of-type(" + indexes + ")").css('color', 'black');   //    rightGuesses.push(space);      }   }    $(".form-control").keypress(function(event) {     var keycode = (event.keyCode ? event.keyCode : event.which);     if (keycode == 13) {       var space = $(this).val();       play(space);       $(this).val('');       endGame();       return false;     }   });     function endGame() {     if (wrongGuesses.length >= 10 || rightGuesses.length == word.length) {       $("body").css("background-color", "#ff4500");       $(".form-control").prop('disabled', true);     }    }  }); html: <header>   <h2 style="font-family:paganini;">     Hangman     </h2> </header> <main style="font-family:paganini;">   <figure class="hangman">     <img src="https://i.imgur.com/gSxmkUf.gif" id="gallows" align="middle top">     <img src="https://i.imgur.com/Mb4owx9.gif" id="head" align="middle top" style="display:none;">     <img src="https://i.imgur.com/xkXISte.gif" id="body" align="middle top" style="display:none;">     <img src="https://i.imgur.com/U44ReUi.gif" id="armL" align="middle top" style="display:none;">     <img src="https://i.imgur.com/49kkaQF.gif" id="handL" align="middle top" style="display:none;">     <img src="https://i.imgur.com/tqtNazW.gif" id="armR" align="middle top" style="display:none;">     <img src="https://i.imgur.com/ydnz7eX.gif" id="handR" align="middle top" style="display:none;">     <img src="https://i.imgur.com/dlL7Kek.gif" id="legL" align="middle top" style="display:none;">     <img src="https://i.imgur.com/3AQYFV9.gif" id="footL" align="middle top" style="display:none;">     <img src="https://i.imgur.com/j9noEN7.gif" id="legR" align="middle top" style="display:none;">     <img src="https://i.imgur.com/kJofX7M.gif" id="footR" align="middle top" style="display:none;">   </figure>    <table class="word-spaces">     <caption>Your Word is: </caption>     <tbody>       <tr>       </tr>     </tbody>   </table>   <br/>   <fieldset class="guessIn">     <legend>       Guess a Letter     </legend>     <label for="form">Type a Letter then Click <b>Enter</b></label>     <input type="text" id="form" class="form-control" placeholder="guess">    </fieldset>    <table class="wrongLetters">     <caption>Letters Guessed Wrong:</caption>     <tbody>       <tr>         <td></td>         <td></td>         <td></td>         <td></td>         <td></td>         <td></td>         <td></td>         <td></td>         <td></td>         <td></td>       </tr>     </tbody>   </table> </main> <footer> </footer> 

回答1:

Note that when you make a selection you get the following error in the console:

Uncaught Error: Syntax error, unrecognized expression: :nth-of-type

That's because of this line:

$(".word-spaces tbody tr td:nth-of-type(" + indexes + ")").css('color', 'black'); 

Since a correct guess can set multiple indexes, you'll need to use a loop for the correct guesses like this:

$.each(indexes,function(e,i){     $(".word-spaces tbody tr td:nth-of-type(" + i + ")").css('color', 'black'); }) 

Additionally, I think this line is wrong:

 $(".word-spaces > tbody > tr").append('<td data-idx=i>' + word[i] + '</td>') 

You probably meant to use the value of i like this:

$(".word-spaces > tbody > tr").append('<td data-idx='+i+'>' + word[i] + '</td>') 

(though you dont really need the data-idx attribute at all since it will always be the same as the child index within the tr tag and you're using that to get the cells anyway)

Here is a working jsFiddle



回答2:

I figured this out on my own (I sort of panicked) like this: first I created a .forEach loop to loop through the word, then the issue was the difference btwn array concatenation in JS & html/css... I creates the index variable, and added one & also an additional plus sign outside of the parenthesis... So, this solves the problem:

indexes.forEach(function(index) { $(".word-spaces tbody tr td:nth-of-type(" + (index + 1) + ")").css('color', 'black'); });



回答3:

Ok, it does everything now. In addition to the first version's features, version 2 has the following:

  • If a letter is guessed wrong more than once, an alert will inform the player of doing so and ignore it.

  • If a correct guess has more than one letter, all letters will be exposed.

  • Improved endGame() function with a message, but it needs one more fix, I'll leave that one to you ;-)

Plunker

<!doctype> <html>  <head>     <meta charset="utf-8">     <title>35387864</title>     <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />     <style>         html {             font: 400 16px/1.428 'Verdana';         }                  main {             padding: 20px;         }                  footer,         header {             padding: 5px 20px;         }                  footer {             border-top: 2px ridge #666;         }                  header {             border-bottom: 2px ridge #666;         }                  .wordSpaces,         .wrongLetters {             border: 1px ridge grey;             table-layout: fixed;             border-collapse: collapse;             margin: 10px 0;         }                  .wordSpaces td,         .wrongLetters td {             border: 2px inset #BBB;             width: 3ch;             height: 1.5rem;             padding: 1px;             text-align: center;             -webkit-user-select: none;             -moz-user-select: none;             -ms-user-select: none;             user-select: none;             color: white;         }                  .wrongLetters td {             color: red;         }                  .form-control {             width: 10ch;             text-align: center;         }                  ul {             font-size: 1rem;             list-style: none;             padding-left: 0;         }                  .msg {             font-size: 0;             color: #000;             text-align: center;         }     </style> </head>  <body>     <header>         <h2> Hangman </h2>     </header>     <main>         <figure class="hangman"> <img src="https://i.imgur.com/gSxmkUf.gif" id="gallows" align="middle top"> <img src="https://i.imgur.com/Mb4owx9.gif" id="head" align="middle top" style="display:none;"> <img src="https://i.imgur.com/xkXISte.gif" id="body" align="middle top" style="display:none;"> <img src="https://i.imgur.com/U44ReUi.gif" id="armL" align="middle top" style="display:none;"> <img src="https://i.imgur.com/49kkaQF.gif" id="handL" align="middle top" style="display:none;"> <img src="https://i.imgur.com/tqtNazW.gif" id="armR" align="middle top" style="display:none;"> <img src="https://i.imgur.com/ydnz7eX.gif" id="handR" align="middle top" style="display:none;"> <img src="https://i.imgur.com/dlL7Kek.gif" id="legL" align="middle top" style="display:none;"> <img src="https://i.imgur.com/3AQYFV9.gif" id="footL" align="middle top" style="display:none;"> <img src="https://i.imgur.com/j9noEN7.gif" id="legR" align="middle top" style="display:none;"> <img src="https://i.imgur.com/kJofX7M.gif" id="footR" align="middle top" style="display:none;"> </figure>         <table class="wordSpaces">             <caption>                 Your Word is:             </caption>             <tbody>                 <tr>                 </tr>             </tbody>         </table>         <br/>         <h1 class="msg"> </h1>         <fieldset class="guessIn">             <legend> Guess a Letter </legend>             <label for="form">Type a Letter then Click <kbd>Enter</kbd></label>             <input type="text" id="form" class="form-control" placeholder="guess" maxlength="1" required/>         </fieldset>         <table class="wrongLetters">             <caption>                 Letters Guessed Wrong:             </caption>             <tbody>                 <tr>                     <td></td>                     <td></td>                     <td></td>                     <td></td>                     <td></td>                     <td></td>                     <td></td>                     <td></td>                     <td></td>                     <td></td>                 </tr>             </tbody>         </table>     </main>     <footer>         <ul>             <li><a href="https://stackoverflow.com/questions/35387864/hangman-gameplay-in-javascript">Hangman Gameplay in JavaScript</a></li>             <li><a href="https://jsfiddle.net/zer00ne/0fa56t3s/">jsFiddle</a></li>         </ul>     </footer>     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>     <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>     <script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>     <script>         var wordBank = ["modernism", "situationalist", "sartre", "camus", "hegel", "lacan", "barthes", "baudrillard", "foucault", "debord", "baudrillard"];         /*var wordBank = ["xxxbnvkllyyybns"];*/         var word = [];         var wrongGuesses = [];         var rightGuesses = [];         var images = [gallows, head, body, armL, handL, armR, handR, legL, footL, legR, footR];         var img = 1;          $(document).ready(function() {             function randomWord() {                 var random = Math.floor(Math.random() * wordBank.length);                 var toString = wordBank[random];                 console.log(toString);                 word = toString.split("");                 console.log(word);             }             randomWord();              function wordSpaces() {                 for (var i = 0; i < word.length; i++) {                     $(".wordSpaces > tbody > tr").append('<td data-idx=i>' + word[i] + '</td>')                 }             }             wordSpaces();              function play(letter) {                 var wIdx = jQuery.inArray(letter, word);                 var wrong = wrongGuesses.length;                 if (wIdx === -1) {                     if (wrong === 0) {                         wrongGuesses.push(letter);                         $('.wrongLetters tbody tr td:first-of-type').text(letter);                         hangman();                     } else {                          for (var j = 0; j < wrong; j++) {                             if (wrongGuesses[j] === letter) {                                 alert('The "' + letter + '" has already beem played.\nPlease try again.');                                 return true;                             }                             console.log('wrong' + wrong);                         }                         wrongGuesses.push(letter);                         $('.wrongLetters tbody tr td:nth-of-type(' + (wrong + 1) + ')').text(letter);                         hangman();                     }                 } else {                     for (var w = 0; w < word.length; w++) {                         if (word[w] === letter) {                             W = w + 1;                             $(".wordSpaces tbody tr td:nth-of-type(" + W + ")").css("color", "black");                             rightGuesses.push(letter);                         }                     }                 }             }             $(".form-control").keypress(function(event) {                 var keycode = (event.keyCode ? event.keyCode : event.which);                 if (keycode == 13) {                     var letter = $(this).val();                     play(letter);                     $(this).val('');                     endGame();                     return false;                 }             });              function hangman() {                 $(images[img - 1]).hide();                 $(images[img]).show();                 img++;                 $("html").css("background-color", "#ff4500").fadeIn(300).delay(300).fadeOut(300).fadeIn(100);             }              function endGame() {                 if (rightGuesses.length == word.length) {                     $("body").css("background-color", "rgba(0, 185, 41, .3)");                     $(".msg").text(word + " is correct!\nYou win!").css("font-size", "24px");                     $(".form-control").prop('disabled', true);                 } else if (wrongGuesses.length === 10) {                     $("body").css("background-color", "rgba(227, 0, 0, .3)");                     $(".msg").text(word + " was the answer.\nYou lose.").css("font-size", "24px");                     $(".form-control").prop('disabled', true);                 } else return false;             }          });     </script> </body>  </html>


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!