[英]Redefining function which is in html <script> element
index.html:索引.html:
<script id="change">
function methods(){
return 1;
}
</script>
js.js: js.js:
...
button.addEventListener("click", ()=>{
document.querySelector("#change").innerHTML = `
function methods(){
return 0;
}
`;
}
...
Console before clicking button:单击按钮前的控制台:
>>>methods();
1
Console after clicking button:单击按钮后的控制台:
>>>methods();
1
How can I update this function?如何更新此功能?
Instead of rewriting the script tag content, just overwrite the methods
function.而不是重写脚本标签内容,只需覆盖methods
功能。
This can be demonstrated easily using the following snippet:这可以使用以下代码段轻松演示:
console.log(methods()); methods = function() { return 0; } console.log(methods());
<script id="change"> function methods(){ return 1; } </script>
In the case of your code, in the event handler just do the same:对于您的代码,在事件处理程序中执行相同的操作:
...
button.addEventListener("click", ()=>{
methods = function() {
return 0;
}
});
...
Edit following OP comment编辑以下 OP 评论
OP has commented stating that the function content is read out of a database and is stored in a string
. OP 已评论指出函数内容是从数据库中读出并存储在string
。 This changes the solution required to:这将所需的解决方案更改为:
console.log(methods()); var functionText = "return 0;"; methods = Function(functionText); console.log(methods());
<script id="change"> function methods(){ return 1; } </script>
In your original code, this would then look like:在您的原始代码中,这将如下所示:
...
button.addEventListener("click", ()=>{
methods = Function("return 0;");
});
...
This is how it works.这就是它的工作原理。
let button = document.querySelector('button'); button.onclick = function() { document.querySelector("#change").innerHTML = ` function methods(){ return 0; } `; }
<script id="change"> function methods(){ return 1; } </script> <button>button</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.