Для редактирования JS и CSS прямо в выходных данных

#javascript

Вопрос:

Вот интересный трюк, как увидеть и отредактировать ваши CSS и JS прямо на выходе. Например, прямо на выходе вы можете изменить цвет с red на blue .

Мой вопрос в том, почему я не могу изменить таким же образом текст, напечатанный сценарием? Я имею в виду, что, независимо от каких-либо изменений, печатный текст остается foo неизменным, а не, например bar . Есть ли способ заставить это работать?

 <div></div>

<p>The contents of the <code>amp;<styleamp;></code> tag:</p>

<style contenteditable>
  div {
    color: red; /* You can change the color right in the **output**! */
  }

  script {
    background: lightgray;
  }

  style {
    background: aliceblue;
  }

  script, style {
    display: inline-block;
    font-family: monospace;
    white-space: pre-wrap;
    width: 100%;
  }
</style>

<p>The contents of the <code>amp;<scriptamp;></code> tag:</p>

<script contenteditable>
  function timer() {
    /* You cannot do the same trick to replace foo with bar... */
    document.querySelector('div').append('foo ');
  }

  setInterval(timer, 1000);
</script>
 

Комментарии:

1. Это чертовски безумно .. может быть, проблема со сценарием в том, что он не перекомпилируется движком после такого изменения?

Ответ №1:

Поскольку script тег выполняется только один раз при вставке в DOM, вы изменяете только его текстовое содержимое, которое не пересматривает значение script . Вы можете эмулировать оценку сценария, но тогда в этом теге нет особого смысла script :

 <div></div>

<p>The contents of the <code>amp;<styleamp;></code> tag:</p>

<style contenteditable>
  div {
    color: red; /* You can change the color right in the **output**! */
  }

  script {
    background: lightgray;
  }

  style {
    background: aliceblue;
  }

  script, style {
    display: inline-block;
    font-family: monospace;
    white-space: pre-wrap;
    width: 100%;
  }
</style>

<p>The contents of the <code>amp;<scriptamp;></code> tag:</p>

<script id="code" contenteditable>
  document.querySelector('div').append('foo ');
</script>

<script>setInterval(() => eval(code.textContent), 1000)</script>