Возвращение случайных строк из массива при нажатии кнопки - PullRequest
0 голосов
/ 07 сентября 2018

Эй, гении StackOverflow!

Может быть, вы можете помочь мне с этим. Я пытаюсь вернуть случайный контент из массивов, когда нажата кнопка «Перемешать». Я могу вернуть содержимое при первом нажатии кнопки, но не при последующих нажатиях. Я знаю, что в моем javascript что-то отсутствует, но я не уверен, что.

var scenarioArray = [
    'Aliens from another planet have invaded and set up their own global government. Humans have been subjugated and now serve the aliens doing hard labor.',
    'Dinosaurs are back and terrorize the global population during daylight hours. They are big, they are mean, and they mean business. Theyve made going outside during the daytime absolutely impossible for humans.',
    'The globe has flooded and land is gone. Those who already owned boats have shaken out to be the leaders of the new global society.'
];
var randomScenario = scenarioArray[Math.floor(Math.random() * scenarioArray.length)];

var controlArray = [
    'All communication between humans is illegal and banned. This includes written, verbal, and electronic forms of communication.',
    'All existing forms of transportation have vanished, and humans are only able to get to where they need to go by walking.',
    'You are being watched. Survillance chips have been implanted into every human brain and they are used to monitor thought and action. Weekly, at the same time the system goes down for maintenance at a secret time. How can you exploit this? '
];
var randomControl = controlArray[Math.floor(Math.random() * controlArray.length)];

var taskArray = [
    'Build a library system that spreads and scales globally.',
    'Build a secret messaging service that can scale globally.',
    'Build a method of transportation that is silent and secret.'
];
var randomTask= taskArray[Math.floor(Math.random() * taskArray.length)];


var shuffle = document.getElementById('shuffle-button');
shuffle.onclick = function() {
    document.getElementById('scenarioScript').innerHTML = randomScenario;
    document.getElementById('controlScript').innerHTML = randomControl;
    document.getElementById('taskScript').innerHTML = randomTask;
}
button {
    margin-top: 3rem;
}

body {
    background-color: #333333;
}

.card-row {
    margin-top: 4rem;
}

.btn-primary {
 /*   background-color: green;*/
}

h1 {
    color: white;
    margin-top: 8rem;
}
<!DOCTYPE html>
<html>
<head>
    <title>Dystopia Cards</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

    <link rel="stylesheet" href="css/index.css">

</head>
<body>

    <div class="container">

        <div class="row">
            <div class="col">
                <h1 class="text-center">Dystopia Generator</h1>
            <div class="col">
        </div>

        <div class="row card-row">
            <div class="col">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">Scenario</h5>
                        <p class="card-text" id="scenarioScript">Click 'Shuffle' button to generate.</p>
                    </div>
                </div>
            </div>
        
            <div class="col">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">Control</h5>
                        <p class="card-text" id="controlScript">Click 'Shuffle' button to generate.</p>
                    </div>
                </div>
            </div>

            <div class="col">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">Task</h5>
                        <p class="card-text" id="taskScript">Click 'Shuffle' button to generate.</p>
                    </div>
                </div>
            </div>
        </div>

        <div class="row justify-content-md-center">
            <div class="col">
                <button class="btn-lg btn btn-primary" id="shuffle-button">Shuffle</button>
            </div>
        </div>

    </div>

</body>

<script src="js/main.js"></script>
</html>

Ответы [ 2 ]

0 голосов
/ 07 сентября 2018

Редактируйте JavaScript следующим образом. Это будет работать:

var scenarioArray = [
    'Aliens from another planet have invaded and set up their own global government. Humans have been subjugated and now serve the aliens doing hard labor.',
    'Dinosaurs are back and terrorize the global population during daylight hours. They are big, they are mean, and they mean business. Theyve made going outside during the daytime absolutely impossible for humans.',
    'The globe has flooded and land is gone. Those who already owned boats have shaken out to be the leaders of the new global society.'
];
var randomScenario = scenarioArray[Math.floor(Math.random() * scenarioArray.length)];

var controlArray = [
    'All communication between humans is illegal and banned. This includes written, verbal, and electronic forms of communication.',
    'All existing forms of transportation have vanished, and humans are only able to get to where they need to go by walking.',
    'You are being watched. Survillance chips have been implanted into every human brain and they are used to monitor thought and action. Weekly, at the same time the system goes down for maintenance at a secret time. How can you exploit this? '
];
var randomControl = controlArray[Math.floor(Math.random() * controlArray.length)];

var taskArray = [
    'Build a library system that spreads and scales globally.',
    'Build a secret messaging service that can scale globally.',
    'Build a method of transportation that is silent and secret.'
];
var randomTask= taskArray[Math.floor(Math.random() * taskArray.length)];

var shuffle = document.getElementById('shuffle-button');
shuffle.onclick = function() {

  //HERE IS THE NEW JAVASCRIPT

  randomScenario = scenarioArray[Math.floor(Math.random() * scenarioArray.length)];
  randomControl = controlArray[Math.floor(Math.random() * controlArray.length)];
  randomTask= taskArray[Math.floor(Math.random() * taskArray.length)];

  //END OF NEW JAVASCRIPT

    document.getElementById('scenarioScript').innerHTML = randomScenario;
    document.getElementById('controlScript').innerHTML = randomControl;
    document.getElementById('taskScript').innerHTML = randomTask;
}

Когда вы нажимаете кнопку, вы устанавливаете innerHTML каждого элемента в три переменные: randomScenario, randomControl, randomTask. Проблема в том, что значение каждой из этих переменных не изменится, когда вы нажмете кнопку, потому что вы уже присвоили значение массива [Math.floor (Math.random () * array.length)]. Вы присвоили это значение только один раз . Вы должны устанавливать значение этих переменных в одну и ту же строку каждый раз, когда нажимаете кнопку, чтобы значения действительно менялись.

0 голосов
/ 07 сентября 2018

Вам нужно выбирать новые randomScenario с и т. Д. При каждом нажатии кнопки - в текущем коде вы выбираете только один сценарий и т. Д. При первом запуске сценария, и затем печатать тот же сценарий, элемент управления и задачу при каждом нажатии кнопки. Создайте новые в вашем onclick обработчике:

var shuffle = document.getElementById('shuffle-button');
shuffle.onclick = function() {
  var randomScenario = scenarioArray[Math.floor(Math.random() * scenarioArray.length)];
  var randomControl = controlArray[Math.floor(Math.random() * controlArray.length)];
  var randomTask = taskArray[Math.floor(Math.random() * taskArray.length)];
  document.getElementById('scenarioScript').innerHTML = randomScenario;
  document.getElementById('controlScript').innerHTML = randomControl;
  document.getElementById('taskScript').innerHTML = randomTask;
}



var scenarioArray = [
  'Aliens from another planet have invaded and set up their own global government. Humans have been subjugated and now serve the aliens doing hard labor.',
  'Dinosaurs are back and terrorize the global population during daylight hours. They are big, they are mean, and they mean business. Theyve made going outside during the daytime absolutely impossible for humans.',
  'The globe has flooded and land is gone. Those who already owned boats have shaken out to be the leaders of the new global society.'
];


var controlArray = [
  'All communication between humans is illegal and banned. This includes written, verbal, and electronic forms of communication.',
  'All existing forms of transportation have vanished, and humans are only able to get to where they need to go by walking.',
  'You are being watched. Survillance chips have been implanted into every human brain and they are used to monitor thought and action. Weekly, at the same time the system goes down for maintenance at a secret time. How can you exploit this? '
];


var taskArray = [
  'Build a library system that spreads and scales globally.',
  'Build a secret messaging service that can scale globally.',
  'Build a method of transportation that is silent and secret.'
];
button {
  margin-top: 3rem;
}

body {
  background-color: #333333;
}

.card-row {
  margin-top: 4rem;
}

.btn-primary {
  /*   background-color: green;*/
}

h1 {
  color: white;
  margin-top: 8rem;
}
<div class="container">

  <div class="row">
    <div class="col">
      <h1 class="text-center">Dystopia Generator</h1>
      <div class="col">
      </div>

      <div class="row card-row">
        <div class="col">
          <div class="card">
            <div class="card-body">
              <h5 class="card-title">Scenario</h5>
              <p class="card-text" id="scenarioScript">Click 'Shuffle' button to generate.</p>
            </div>
          </div>
        </div>

        <div class="col">
          <div class="card">
            <div class="card-body">
              <h5 class="card-title">Control</h5>
              <p class="card-text" id="controlScript">Click 'Shuffle' button to generate.</p>
            </div>
          </div>
        </div>

        <div class="col">
          <div class="card">
            <div class="card-body">
              <h5 class="card-title">Task</h5>
              <p class="card-text" id="taskScript">Click 'Shuffle' button to generate.</p>
            </div>
          </div>
        </div>
      </div>

      <div class="row justify-content-md-center">
        <div class="col">
          <button class="btn-lg btn btn-primary" id="shuffle-button">Shuffle</button>
        </div>
      </div>

    </div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...