Выбор элемента узла в JavaScript - PullRequest
0 голосов
/ 02 января 2019

Я пытаюсь построить генератор цитат и пытаюсь взять цитаты из коллекции абзацев HTML.

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

Это моя попытка рандомизации:

const quotes = quotesdocument.querySelectorAll("p");

const randomize = function() {
  for(quote of quotes) {
    let num = (Math.floor(Math.random() * Math.floor(quotes.length)) - 1);
    console.log(quotes.item(num));
  }
}

И это и отрывок из HTML, который я пытаюсьrandomize:

<p>&#8220;<a href="https://theunboundedspirit.com/ananda-coomaraswamy-quotes/">Art</a> is the supreme task and the truly metaphysical activity in this life.&#8221;</p>
<p>&#8220;Underneath this reality in which we live and have our being, another and altogether different reality lies concealed.&#8221;</p>
<p>&#8220;We obtain the concept, as we do the form, by overlooking what is individual and actual; whereas nature is acquainted with no forms and no concepts, and likewise with no species, but only with an X which remains inaccessible and undefinable for us.&#8221;</p>
<p>&#8220;Everything which distinguishes man from the animals depends upon this ability to volatilize perceptual metaphors in a schema, and thus to dissolve an image into a concept.&#8221;</p>
<p>&#8220;Our destiny exercises its influence over us even when, as yet, we have not learned its nature: it is our future that lays down the law of our today.&#8221;</p>

Я ожидал получить только один из этих абзацев, но продолжаю получать их все.

Спасибо за помощь.

Ответы [ 2 ]

0 голосов
/ 02 января 2019

Цикл for..of, который есть в вашем коде, не нужен.Просто используйте код, который у вас уже есть, и num в качестве значения индекса массива quotes.Я добавил кнопку, чтобы продемонстрировать, как функция будет возвращать только одно значение:

function randomQuote() {
  const quotes = document.querySelectorAll("p");
  const num = (Math.floor(Math.random() * Math.floor(quotes.length)));
  return quotes[num].innerText;
}

document.querySelector('#buttonEl').addEventListener('click', () => {
  document.querySelector('#quoteEl').innerHTML = randomQuote();
});
#quoteEl {
  color: red;
}
<input id="buttonEl" type="button" value="Click for a random quote from the list below" />
<div id="quoteEl"></div>
<p>&#8220;<a href="https://theunboundedspirit.com/ananda-coomaraswamy-quotes/">Art</a> is the supreme task and the truly metaphysical activity in this life.&#8221;</p>
<p>&#8220;Underneath this reality in which we live and have our being, another and altogether different reality lies concealed.&#8221;</p>
<p>&#8220;We obtain the concept, as we do the form, by overlooking what is individual and actual; whereas nature is acquainted with no forms and no concepts, and likewise with no species, but only with an X which remains inaccessible and undefinable for
  us.&#8221;
</p>
<p>&#8220;Everything which distinguishes man from the animals depends upon this ability to volatilize perceptual metaphors in a schema, and thus to dissolve an image into a concept.&#8221;</p>
<p>&#8220;Our destiny exercises its influence over us even when, as yet, we have not learned its nature: it is our future that lays down the law of our today.&#8221;</p>
0 голосов
/ 02 января 2019

Причина, по которой это не работает, в том, что вы перебираете все кавычки.Удаление цикла for и изменение логики рандомизации исправит это:

const quotes = document.querySelectorAll("p");

const randomize = function() {
  let num = Math.floor(Math.random() * quotes.length) - 1;
  console.log(quotes.item(num).innerText);
}

randomize();
<p>&#8220;<a href="https://theunboundedspirit.com/ananda-coomaraswamy-quotes/">Art</a> is the supreme task and the truly metaphysical activity in this life.&#8221;</p>
<p>&#8220;Underneath this reality in which we live and have our being, another and altogether different reality lies concealed.&#8221;</p>
<p>&#8220;We obtain the concept, as we do the form, by overlooking what is individual and actual; whereas nature is acquainted with no forms and no concepts, and likewise with no species, but only with an X which remains inaccessible and undefinable for
  us.&#8221;</p>
<p>&#8220;Everything which distinguishes man from the animals depends upon this ability to volatilize perceptual metaphors in a schema, and thus to dissolve an image into a concept.&#8221;</p>
<p>&#8220;Our destiny exercises its influence over us even when, as yet, we have not learned its nature: it is our future that lays down the law of our today.&#8221;</p>

В вышеприведенном фрагменте я console.log() текст text внутри элемента, чтобы вы могли видеть, как он работает, но дляполучить доступ к самому элементу, просто удалите innerText, который я там поместил.

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