在javascript中使用eval的替代方法

CSP*_*LJS 0 javascript eval function onclick

我听说在JavaScript中使用eval函数是个坏主意,但我有这个代码:

// this string (function)  is generated dynamically...
var funVal = 'alert("a")' ;        
//.....

var Button1 = document.getElementById("BtnSave");
// onclick event of button
eval("Button1.onclick = function () { " + funVal + " };");  
Run Code Online (Sandbox Code Playgroud)

我不想用eval.还有其他解决方案吗?

T.J*_*der 5

只需编写非常接近的代码eval,没有什么需要它:

var funVal = function() {
    alert("a");
};

var Button1 = document.getElementById("BtnSave");
Button1.onclick = funVal;
Run Code Online (Sandbox Code Playgroud)

在评论中,您已经说过代码是动态生成的服务器端.这根本不是问题,只需让服务器输出预期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>
Run Code Online (Sandbox Code Playgroud)

实例

示例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>
Run Code Online (Sandbox Code Playgroud)

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)); ?>");
};
Run Code Online (Sandbox Code Playgroud)

实例