insertAdjacent HTML стирает функции со страницы так же, как document.write - PullRequest
1 голос
/ 03 августа 2020

У меня был предыдущий вопрос, и кто-то сказал мне, что document.write стирает все функции и вместо этого использовал insertAdjacent HTML, но когда я попробовал, он дал тот же результат. Код по-прежнему говорит, что myFunction не определена. Что я делаю не так?

// ==UserScript==
// @name         Replace Multiple Spaces With One Space
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://www.google.com/search?q=replaceSpace
// @grant        none
// ==/UserScript==

document.body.insertAdjacentHTML("beforeEnd", "<input type='text' id='myText' value='Some text...'>");
document.body.insertAdjacentHTML("beforeEnd", "<p id='demo'></p>");
document.body.insertAdjacentHTML("beforeEnd", "<button onclick='myFunction()'>Try it</button>");

function myFunction() {
  var string = document.getElementById("myText").value;
  string = string.replace(/\s\s+/g, ' ');
  document.getElementById("demo").innerHTML = string;
}

1 Ответ

1 голос
/ 03 августа 2020
(function() {
    const myText = document.createElement("input"),
        demo = document.createElement("p"),
        button = document.createElement("button");
    myText.type = "text";
    myText.value = "Some text...";
    button.textContent = "Try it";
    button.addEventListener("click", () => demo.innerHTML = myText.value.replace(/\s{2,}/g, " "));
    document.body.insertAdjacentElement("beforeend", myText);
    document.body.insertAdjacentElement("beforeend", demo);
    document.body.insertAdjacentElement("beforeend", button);
})();
...