只需在没有 的情况下编写非常接近的代码eval
,就没有什么需要它了:
var funVal = function() {
alert("a");
};
var Button1 = document.getElementById("BtnSave");
Button1.onclick = funVal;
在您所说的评论中,代码是在服务器端动态生成的。这根本不是问题,只需让服务器输出预期 JavaScript 代码的代码(在<script>...</script>
标签内,或作为您将通过 加载的响应的完整内容<script src="..."></script>
)。无论哪种情况,关键是确保您发送给浏览器的内容是有效代码。
示例 1:动态生成的内联script
标签(您还没有说服务器端技术是什么,所以我选择了相当常见的 PHP):
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Inline Dynamically Generated Script</title>
</head>
<body>
<p>Each time you load this page, the script in the inline
<code>script</code> tag at the end is different.</p>
<button id="theButton">Click Me</button>
<script>
document.getElementById("theButton").onclick = function() {
alert("<?php echo("Hi there, this page's magic number is " . rand(0, 10000)); ?>");
};
</script>
</body>
</html>
现场示例
示例 2:在单独文件中动态生成的脚本:
HTML:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Dynamically Generated Script from File</title>
</head>
<body>
<p>Each time you load this page, the script in the file
loaded by the <code>script</code> tag at the end
is different.</p>
<button id="theButton">Click Me</button>
<script src="dynamic-script.php"></script>
</body>
</html>
JavaScript 文件 ( dynamic-script.php
):
<?php header('Content-type: application/javascript'); ?>
document.getElementById("theButton").onclick = function() {
alert("<?php echo("Hi there, this page's magic number is " . rand(0, 10000)); ?>");
};
现场示例