在 JavaScript 中按名称调用函数
在 JavaScript 中,有时将函数名存储在字符串中很方便,因为我们可以使用这些字符串来调用实际的函数。
我们可以使用 eval()
方法调用一个名称存储在字符串变量中的 JavaScript 函数,但它是一个旧方法。
我们将使用 window object
方法来调用函数。
在 JavaScript 中使用 window object
方法按名称调用函数
我们创建了一个名为 changeColor()
的函数。我们将该函数存储在字符串变量中。
现在,我们要调用我们存储在字符串中的那个函数。我们需要点击按钮。
在字符串函数中,我们传递参数 red。因此,当我们单击按钮时,文本 You called the Function
的颜色变为红色。
<!DOCTYPE html>
<html>
<head>
<title>
To call a function
</title>
</head>
<body>
<h1 style="color: Red">
Call function by name
</h1>
<b>
To call a function by its name stored in string variable in JavaScript.
</b>
<p>
Click on the button to call the function in the string.
</p>
<p class="example">
You called the function.
</p>
<button onclick="evaluateFunction()">
Click Here
</button>
<script type="text/javascript">
function changeColor(color) {
document.querySelector('.example').style
= `color: ${color}`;
}
function evaluateFunction() {
stringFunction = "changeColor";
param = 'red';
window[stringFunction](param);
}
</script>
</body>
</html>
这样,我们通过使用 window[stringFunction](param)
方法调用字符串函数。
输出:
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。