如何完全替换 JavaScript 中的函数?
我得到了这个代码,但它不起作用。不过,DOM 会更新。这是怎么回事?
<html>
<head>
<script id="myScript" type="text/javascript">
function someFunction() {
alert("Same old.");
}
</script>
</head>
<body>
<input type="button" onclick="someFunction();" value="A button." />
<script>
function replace() {
var oldFunctionString = someFunction.toString();
var oldContents = oldFunctionString.substring(oldFunctionString.indexOf("{") + 1, oldFunctionString.lastIndexOf("}") );
var newCode = "alert(New code!);";
var newFunctionString = "function someFunction(){"+newCode+"}";
var scriptTag = document.getElementById('myScript');
scriptTag.innerHTML = scriptTag.innerHTML.replace(oldFunctionString,newFunctionString);
}
replace();
</script>
</body>
</html>
JSfiddle here
最佳答案
设置.innerHTML
不会重新执行脚本。如果你真的想这样做,你必须创建一个新的 script
元素并将其附加到 DOM,然后覆盖之前的脚本所做的事情(当然,不可能在所有情况下) )。
如果你想替换该函数,只需使用
somefunction = function() {
alert(New code!); // syntax error, btw
};
当然,要仅替换部分代码(不知道全部代码),您可以尝试 regex 和 co。仍然只需将新函数重新分配给变量即可:
somefunction = eval("("
+ somefunction.toString().replace(/(alert\().*?(\);)/, "$1New code!$2")
+ ")");
关于javascript - 在 JavaScript 中动态替换函数内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13211151/