简体   繁体   English

如何使用 JavaScript 在 HTML 中用另一个脚本标签替换脚本标签?

[英]How to replace a script tag with another in HTML with JavaScript?

I would like to run a javascript code that replaces a certain string with another string, editing the page.我想运行一个 javascript 代码,用另一个字符串替换某个字符串,编辑页面。 I can do such easily with a string:我可以用一个字符串轻松做到这一点:

  var documentHTMLupdated = documentHTML.replace(originalString, newString);

but I need to have the html update.但我需要更新 html。 Calling document.write() again with the updated HTML does not work, as I don't want to have to reload the entire page (plus google chrome gets mad when I call document.write() ).使用更新的 HTML 再次调用document.write()不起作用,因为我不想重新加载整个页面(加上 google chrome 当我调用document.write()时会发疯)。 How can I update my HTML, only knowing the string I want to replace (no knowlede of element ID, etc), without calling document.write()?如何更新我的 HTML,只知道我想替换的字符串(不知道元素 ID 等),而不调用 document.write()?

It would look something like:它看起来像:

<script> somefunction(); </script>

to

<script> updatedfunction(); </script>

Thank you for the help!感谢您的帮助! (And my apologies if I asked this question poorly. I believe it fits community guidelines, but let me know if it doesn't so I can correct my mistakes) (如果我问这个问题很糟糕,我很抱歉。我相信它符合社区准则,但如果不符合请告诉我,以便我可以纠正我的错误)

Instinctively I would loop on all text nodes and run a replace method on them.本能地,我会在所有文本节点上循环并在它们上运行替换方法。 I'm not sure of the efficiency of this but on a small page it shouldn't be so heavy.我不确定这样做的效率,但在一个小页面上它不应该那么重。 You can use getElementsByTagName to get all span, p, li.您可以使用getElementsByTagName获取所有跨度、p、li。

Not very elegant but should work without having to reload the page.不是很优雅,但应该无需重新加载页面即可工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM