JS Magic 8 Ball Игры на выходе - PullRequest
       73

JS Magic 8 Ball Игры на выходе

0 голосов
/ 16 октября 2018

Я создаю волшебную игру с 8 мячами, и у меня возникают проблемы с форматированием вывода.Моя программа выбирает случайный ответ и выводит его как следует.Пользователь вводит свое имя и вопрос, и я хочу получить вывод: name + Ответ на inputted question + - это + случайно сгенерированный ответ.Как я могу объединить эти элементы вместе, чтобы отформатировать вывод.Я попытался использовать +, и это заставляет мой вывод исчезнуть.

<!DOCTYPE html>
<!-- =================================================== -->
<html>
<head>
    <link rel="stylesheet" type="text/css" href="../myStyles/styles.css">
    <title> Magic 8 Ball </title>
    <meta charset = "UTF-8">
    </head>
    <script>


        function GenerateAnswer()
        {
            var responses = [
                'It is certain',
                'It is decidedly so',
                'Without a doubt',
                'Yes definitely',
                'You may rely on it',
                'As I see it, yes',
                'Most likely',
                'Outlook good',
                'yes',
                'Signs point to yes',
                'Reply hazy try again',
                'Ask again later',
                'Better not tell you now',
                'Cannot predict now',
                'Concentrate and ask again',
                'Do not count on it',
                'My reply is no',
                'My sources say no',
                'Outlook not so good',
                'Very doubtful',
                ];
        var choice = responses[Math.floor(Math.random()*responses.length)];
        document.getElementById("response").innerHTML = choice
        }
    </script>

<body>

<h1 style = "text-align:left;">Magic 8 Ball...</h1>
<h2 style = "text-align:left;">Ask me a question and I will predict if it will become true!</h2>
<p style = "text-align:left;">Please enter your name:</p>
<input type = "text" id="nameBox" size=100 value= ''>
<h2 id = "name"></h2>
<p style = "text-align:left;">What is your question?</p>
<input type="text" id="questionBox" size=100 value=''>
<input type="button" id="submit" value = "Ask me a question" onclick="GenerateAnswer()" ;>
<h2 id = "response"></h2>

Ответы [ 2 ]

0 голосов
/ 16 октября 2018

Вот как я понимаю, чего вы хотите достичь:

function makeOutput(userName, generatedChoice, inputtedQuestion) {
   // You can avoid this if statement if you don't require it.
   if(!userName || !generatedChoice || inputtedQuestion) return null; 

   return `${userName} The answer to ${inputtedQuestion} is ${generatedChoice}`
}

Если этот синтаксис кажется вам странным, это литерал шаблона, который является функцией ES2015.Проверьте здесь

Затем вызовите

makeOutput('Name', 'It is certain') // Name The answer to inputted question is It is certain.

Конечно, аргументы должны быть динамическими, то есть получить name иquestion из html элементов!

Дайте мне знать, если это не ясно.

0 голосов
/ 16 октября 2018

Вам нужно взять имя из id #nameBox и запустить его в своем внутреннем HTML.

            function GenerateAnswer()
            {
                var responses = [
                    'It is certain',
                    'It is decidedly so',
                    'Without a doubt',
                    'Yes definitely',
                    'You may rely on it',
                    'As I see it, yes',
                    'Most likely',
                    'Outlook good',
                    'yes',
                    'Signs point to yes',
                    'Reply hazy try again',
                    'Ask again later',
                    'Better not tell you now',
                    'Cannot predict now',
                    'Concentrate and ask again',
                    'Do not count on it',
                    'My reply is no',
                    'My sources say no',
                    'Outlook not so good',
                    'Very doubtful',
                    ];
            var choice = responses[Math.floor(Math.random()*responses.length)];
            var name = document.querySelector("#nameBox").value;
            document.getElementById("response").innerHTML = name + ', The answer to your question is: ' + choice
            }
    <!DOCTYPE html>
    <html>
    <head>
        <link rel="stylesheet" type="text/css" href="../myStyles/styles.css">
        <title> Magic 8 Ball </title>
        <meta charset = "UTF-8">
        </head>
    <body>

    <h1 style = "text-align:left;">Magic 8 Ball...</h1>
    <h2 style = "text-align:left;">Ask me a question and I will predict if it will become true!</h2>
    <p style = "text-align:left;">Please enter your name:</p>
    <input type = "text" id="nameBox" size=100 value= ''>
    <h2 id = "name"></h2>
    <p style = "text-align:left;">What is your question?</p>
    <input type="text" id="questionBox" size=100 value=''>
    <input type="button" id="submit" value = "Ask me a question" onclick="GenerateAnswer()" ;>
    <h2 id = "response"></h2>
...