所以我一直在尝试学习一些javascript,并一直在研究一个非常(非常)基本的用户脚本,它只是简单地改变一个网站(不是我控制源的网站)上链接的文本颜色。问题是,当脚本运行时,它改变了链接的文本颜色,链接仍然工作,但附近的一些功能元素完全停止工作(搜索栏预览,搜索按钮,配置文件下拉列表)。
document.body.innerHTML= document.body.innerHTML.replace(/Advanced\n\s{1,}Search/,"\<span style\=\"color\: \#2898FF\"\> Advanced Search \<\/span\>");
我还试着把脚本当作书签来运行,以防万一,用户脚本的运行方式有什么问题,以及与之相关的元数据,但是没有,同样的情况。
当你这样做的时候,页面上的所有元素都会被重新创建,所以在页面上的大多数JavaScript事件监听器上的改变将不再工作。
document.getElementById('click').onclick = () => {
console.log('Click!');
};
document.getElementById('replace').onclick = () => {
console.log('Replace!');
document.body.innerHTML= document.body.innerHTML.replace(
/Advanced\n\s{1,}Search/,
'\<span style\=\"color\: \#2898FF\"\> Advanced Search \<\/span\>'
);
};
.as-console-wrapper {
max-height: 45px !important;
}
<h1>
Advanced
Search
</h1>
<button id="click">Click me!</button>
<button id="replace">Replace HTML</button>
取而代之的是,找到你想要更新的元素 然后改变它们的一些属性。
const h1 = document.querySelector('h1');
document.getElementById('click').onclick = () => {
console.log('Click!');
};
document.getElementById('replace').onclick = () => {
console.log('Replace!');
h1.textContent = 'Advanced Search';
h1.style.color = ['red', 'yellow', 'green', 'cyan', 'blue', 'magenta'][Math.round(Math.random() * 5)];
};
.as-console-wrapper {
max-height: 45px !important;
}
<h1>
Advanced
Search
</h1>
<button id="click">Click me!</button>
<button id="replace">Replace HTML</button>