如何在网页中动态更新和执行javascript代码?

如何在网页中动态更新和执行javascript代码?,javascript,Javascript,我有一个带有标签的网站 <script id='text1' type='text/javascript'></script> 单击一个按钮,它将在代码的命名空间中执行一个函数 var namespace1 = {}; (function(context) { context.getGameName = function() { return ('text'); }; })(namespace1); 一切正常,但是如果我尝试更改中的文

我有一个带有
标签的网站

<script id='text1' type='text/javascript'></script>
单击一个按钮,它将在
代码的命名空间中执行一个函数

var namespace1 = {};
(function(context) {
    context.getGameName = function() {
        return ('text');
    };

})(namespace1);
一切正常,但是如果我尝试更改
中的文本并更新
标记的内容,我可以在控制台中看到DOM中的内容正在更新,但是当再次单击按钮执行代码时,会执行旧代码,而不是新代码


如何更新javascript并执行同名函数的新版本?

要定义同名函数的新版本,只需重新声明它(以下是其中一种方法):


您无需更改包含的某些脚本标记的内容。

当节点第一次插入DOM时,将评估
脚本
标记内容,而不是每次更改其内容时

您需要使用新内容创建一个新的脚本标记,删除旧的脚本标记并将新的脚本标记插入DOM

var s = document.createElement("script");
s.textContent = "console.log('Hello,');"
document.body.append(s); // Will display "Hello," on console
document.body.removeChild(s);

s = document.createElement("script");  // <<-- create a new node
s.textContent = "console.log('world.');"
document.body.append(s); // Will display "world." on console
var s=document.createElement(“脚本”);
s、 textContent=“console.log('Hello')
document.body.append(s);//将在控制台上显示“Hello”
文件.正文.删除儿童;

s=document.createElement(“脚本”);//请使用可运行的堆栈片段更新您的问题(使用
[]
工具栏按钮)。很难说什么代码在哪里运行。从根本上说,一旦代码被解析并运行,它所产生的任何持久效果(如创建函数)都将成为JavaScript环境当前状态的一部分。与CSS规则不同,删除该脚本不会删除它所具有的效果。太好了!一切正常。感谢对插入而不是修改的评估的解释。谢谢
var namespace1 = {};
(function(context) {
    context.getGameName = function() {
        return ('text');
    };

})(namespace1);
var newScript = document.createElement('script');
newScript.innerHTML = document.getElementById('text2').getElementsByClassName('text3')[0].value;
document.body.appendChild(newScript);
var s = document.createElement("script");
s.textContent = "console.log('Hello,');"
document.body.append(s); // Will display "Hello," on console
document.body.removeChild(s);

s = document.createElement("script");  // <<-- create a new node
s.textContent = "console.log('world.');"
document.body.append(s); // Will display "world." on console