我有一个先前的问题,有人告诉我 document.write 会清除所有功能,并改用 insertAdjacentHTML,但是当我尝试时,结果相同。代码仍然说 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;
}