Как повторно вызвать функцию генерации с помощью кнопок onclick - PullRequest
0 голосов
/ 11 апреля 2020

Я пытаюсь создать генератор случайных предложений, который выбирает случайное прилагательное, существительное и глагол в соответствующем месте.

В первый раз, он идеально генерирует предложение и дает кнопку для генерации снова , Когда я нажимаю на эту кнопку, ничего не происходит. Я не уверен, почему.

Было бы также лучше, если бы в первом поколении, при первом нажатии кнопки, предложение просто добавлялось к тому, что уже есть, и текст на кнопке меняется на " «Создайте другое» вместо «Создайте предложение». Затем, когда вы снова нажмете кнопку, предложение автоматически изменится.

Если есть кто-нибудь, кто мог бы изучить мой код и помочь мне, но это было бы здорово, спасибо:

var nouns = ["girl", "boy", "man", "woman", "animal"];
var adjectives = ["giant", "tiny", "funny", "sad", "strange"];
var verbs = ["jumping", "running", "smiling", "exploding", "dying"];

document.write(
  "Welcome to the Useless Random Sentence Generator! More words and combinations will be added in the future. You can always email liorpoliti24@gmail.com for verb, noun, and adjective suggestions as well as other suggestions to make this generator better. Click the button to begin."
);

function randIndex() {
  var randIndex = Math.floor(Math.random() * 5);
  var noun = nouns[randIndex];
  var adjective = adjectives[randIndex];
  var verb = verbs[randIndex];
  var result = "The " + adjective + " " + noun + " is " + verb + ".";
  document.write(result);

  elem = document.createElement("hr");
  elem.setAttribute("width", "500px");
  elem.setAttribute("legth", "8000px");
  document.body.appendChild(elem);

  const btn = document.createElement("button");
  btn.innerText = "Generate Another";
  document.body.appendChild(btn);
  btn.innerText = "Generate Another";
  btn.addEventListener("click", () => {
    randIndex();
  });
}
<button onclick="randIndex();">
   Generate Random Sentence
</button>

Ответы [ 2 ]

1 голос
/ 11 апреля 2020

Это работает:

    var nouns = ["girl", "boy", "man", "woman", "animal"];
    var adjectives = ["giant", "tiny", "funny", "sad", "strange"];
    var verbs = ["jumping", "running", "smiling", "exploding", "dying"];

    function randIndex() {
      var randIndex = Math.floor(Math.random() * 5);
      var noun = nouns[randIndex];
      var adjective = adjectives[randIndex];
      var verb = verbs[randIndex];
      var result = "The " + adjective + " " + noun + " is " + verb + "."
      var li = document.createElement("li");
      li.innerHTML = result;
document.getElementById("result").appendChild(li);

document.getElementById("generateButton").value = "Generate another";
    }
<div>
"Welcome to the Useless Random Sentence Generator! More words and combinations will be added in the future. You can always email liorpoliti24@gmail.com for verb, noun, and adjective suggestions as well as other suggestions to make this generator better. Click the button to begin."
</div>
<ul id="result"></ul>
    <input type="button" id="generateButton" onclick="randIndex();" value="Generate Random Sentence" />
0 голосов
/ 11 апреля 2020

Добро пожаловать в Paradox Blu! Довольно хорошее начало. Достаточно информации для эффективной помощи!

Как насчет этого? Я позволил себе добавить, помимо прочего, немного больше контекста HTML.

Начальный элемент div кажется более подходящим, чем использование document.write (), который не поддерживается в high Я считаю, что в наши дни.

Я дал идентификаторы элемента кнопки (и элемента ul), потому что довольно просто использовать функции JS (например, document.getElementById) для идентификации и манипулирования этим способом.

Элемент ul мог бы быть обычным div, section - практически чем угодно. Элементы ul, естественно, содержат кучу элементов li, поэтому они, кажется, подходят.

Вы уже создали и добавили несколько новых элементов button в свой собственный код, поэтому я не думаю, что мне нужно много говорить об этом.

<div>
  <p>Welcome to the Useless Random Sentence Generator!
     More words and combinations will be added in the
     future. You can always email for verb, noun, and
     adjective suggestions as well as other suggestions
     to make this generator better.
     Click the button to begin.</p>
</div>

<button id="btn" onclick="randIndex();">
    Generate Random Sentence
</button>

<ul id="sent">
</ul>

Затем, в разделе сценариев:

const nouns = ["girl", "boy", "man", "woman", "animal"];
const adjectives = ["giant", "tiny", "funny", "sad", "strange"];
const verbs = ["jumping", "running", "smiling", "exploding", "dying"];


function randIndex() {
    const randIndex = Math.floor(Math.random() * 5);
    const noun = nouns[randIndex];
    const adjective = adjectives[randIndex];
    const verb = verbs[randIndex];
    const btn = document.getElementById('btn');
    const sent = document.getElementById('sent');
    const result = "The " + adjective + " " + noun + " is " + verb + ".";

    const newLI = document.createElement("li");
    newLI.innerText = result;
    sent.appendChild(newLI);
    btn.innerText = "Generate Another";
}

Я, вероятно, должен добавить снимок того, как выглядит вывод, быстрый и грязный, хотя это: after clicking the button a few times

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