Почему мои манипуляции с DOM не работают в JavaScript? - PullRequest
0 голосов
/ 02 января 2019

Я пытаюсь заменить список абзацев только одним случайным абзацем, но по какой-то причине код JavaScript не сработает.

Я попытался переставить переменные после завершения функции, но я не могу понять, что не так.

Вот так начинаются мои HTML-элементы:

<body>
  <div id = "quotes">
    <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>

И это моя попытка манипулирования DOM:

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

const randomize = function() {
  let num = (Math.floor(Math.random() * Math.floor(quotes.length)) - 1);
  let quote = quotes.item(num).innerHTML;
return quote;
}
let randomQuote = randomize();
let passage = document.getElementById('quotes').innerHTML;
passage = randomQuote;
console.log(randomQuote);

Ответы [ 4 ]

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

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

Просто измените это:

let passage = document.getElementById('quotes').innerHTML;

до:

document.getElementById('quotes').innerHTML= randomQuote;
0 голосов
/ 02 января 2019

Проблема в том, что

let passage = document.getElementById('quotes').innerHTML;

Устанавливает значение перехода к мгновенному значению innerHTML кавычек, это не ссылка (что невозможно в javascript, кстати).

passage = randomQuote;

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

document.getElementById('quotes').innerHTML = randomQuote;
0 голосов
/ 02 января 2019

Проблема заключается здесь:

let passage = document.getElementById('quotes').innerHTML;
passage = randomQuote;

Вы должны сделать:

let passage = document.getElementById('quotes');
passage.innerHTML = randomQuote;

Почему

В этой строке:

let passage = document.getElementById('quotes').innerHTML;

На самом деле вы получаете ссылку на строку от .innerHTML до passage, а не сам элемент.

Поэтому в следующей строке:

passage = randomQuote;

Вы заменяете строку только другой строкой, а не заменяете значение свойства элемента.Поскольку passage не является элементом, это строка.

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

Единственный способ изменить HTML узла (с помощью innerHTML) - это присвоить его свойству innerHTML, которое вызывает внутреннюю операцию установки. Извлечение innerHTML узла в переменную с последующим переназначением этой переменной ничего не даст. (переназначение ссылки на переменную на что-то другое само по себе ничего не изменит.)

Итак, используйте

document.getElementById('quotes').innerHTML = randomQuote;

Вам также необходимо исправить num генератор случайных чисел - используйте Math.floor(Math.random() * quotes.length); для генерации числа от 0 до quotes.length - 1, в противном случае num иногда будет -1 (чей индекс не существует, из курс):

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

const randomize = function() {
  const num = Math.floor(Math.random() * quotes.length);
  return quotes.item(num).innerHTML;
}
const randomQuote = randomize();
document.getElementById('quotes').innerHTML = randomQuote;
<body>
  <div id="quotes">
    <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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...