为什么我们在 javascript 中的函数参数中使用引号?
why we are using quotes inside a parameter for a function in javascript?
<head>
<script type="text/javascript">
<!--
function Redirect()
{
window.location="http://www.newlocation.com";
}
document.write("You will be redirected to main page in 10 sec.");
setTimeout('Redirect()', 10000);
//-->
</script>
</head>
1.Here 我的问题是在 settimeout 方法中我们如何使用函数来调用,如果我们在单引号内使用字符串文字我认为这代表写出像 document.write("hello");
这样的确切结果现在结果将与字符串中的一样.. javascript 如何将 setTimeout('Redirect()', 10000);
'redirect()' 理解为一种方法,而不是按原样编写..
<head>
<script type="text/javascript">
<!--
function Redirect() {
window.location="http://www.tutorialspoint.com";
}
document.write("You will be redirected to our main page in 10 seconds!");
setTimeout(Redirect(), 10000);
//-->
</script>
</head>
<body>
</body>
</html>
2.When 我喜欢这样 setTimeout(Redirect(), 10000);
,它不起作用...它开始直接重定向页面而不是使用 settimeout 它...
我们只需要传递函数名(不带括号),这样写:
setTimeout(Redirect, 10000);
它会起作用。
您的代码立即调用 Redirect()
的原因是因为它在 setTimeout
为 运行 时进行计算。
您可以采取的措施是传递一个匿名函数来环绕该方法。像这样:setTimeout(function(){ Redirect(); }, 10000);
这 link 解释了为什么您的字符串 "Redirect()"
会按照您的预期进行计算。简而言之(取自 link):字符串文字在全局上下文中使用 eval
求值。
WindowTimers.setTimeout()
如果不加引号:setTimeout(yourFunction(),1000)
浏览器会立即运行该函数,因为它是直接调用。
如果写在引号中,setTimeout-js-method 会解释字符串并在超时后调用它。
你可以写setTimeout(yourFunction, 1000)
。这样可行。但是考虑一下,在这种情况下你不能传递任何参数。
为了解决这个问题,您可以将参数写入一个 var 中,您的 timeouthandler 可以在它运行时读取它:
yourFunction(){
alert(param);
}
var param="Hello";
setTimeout(yourFunction, 1000);
问候安德烈
<head>
<script type="text/javascript">
<!--
function Redirect()
{
window.location="http://www.newlocation.com";
}
document.write("You will be redirected to main page in 10 sec.");
setTimeout('Redirect()', 10000);
//-->
</script>
</head>
1.Here 我的问题是在 settimeout 方法中我们如何使用函数来调用,如果我们在单引号内使用字符串文字我认为这代表写出像 document.write("hello");
这样的确切结果现在结果将与字符串中的一样.. javascript 如何将 setTimeout('Redirect()', 10000);
'redirect()' 理解为一种方法,而不是按原样编写..
<head>
<script type="text/javascript">
<!--
function Redirect() {
window.location="http://www.tutorialspoint.com";
}
document.write("You will be redirected to our main page in 10 seconds!");
setTimeout(Redirect(), 10000);
//-->
</script>
</head>
<body>
</body>
</html>
2.When 我喜欢这样 setTimeout(Redirect(), 10000);
,它不起作用...它开始直接重定向页面而不是使用 settimeout 它...
我们只需要传递函数名(不带括号),这样写:
setTimeout(Redirect, 10000);
它会起作用。
您的代码立即调用 Redirect()
的原因是因为它在 setTimeout
为 运行 时进行计算。
您可以采取的措施是传递一个匿名函数来环绕该方法。像这样:setTimeout(function(){ Redirect(); }, 10000);
这 link 解释了为什么您的字符串 "Redirect()"
会按照您的预期进行计算。简而言之(取自 link):字符串文字在全局上下文中使用 eval
求值。
WindowTimers.setTimeout()
如果不加引号:setTimeout(yourFunction(),1000)
浏览器会立即运行该函数,因为它是直接调用。
如果写在引号中,setTimeout-js-method 会解释字符串并在超时后调用它。
你可以写setTimeout(yourFunction, 1000)
。这样可行。但是考虑一下,在这种情况下你不能传递任何参数。
为了解决这个问题,您可以将参数写入一个 var 中,您的 timeouthandler 可以在它运行时读取它:
yourFunction(){
alert(param);
}
var param="Hello";
setTimeout(yourFunction, 1000);
问候安德烈