javascript - 将函数作为参数传递时使用字符串

标签 javascript string function arguments

以下脚本(由 Adam Khoury 提供)创建一个计时器,在完成时给出一条消息。该功能对我来说很有意义,但我很难理解这里字符串的使用。特别是:

1) 为什么必须将 'countDown('+secs+',"'+elem+'")' 作为字符串传递?在我见过的其他示例中,setTimeout 可以接受一个函数(不带“引号”)。

2) 同样,在同一行中,为什么必须将 elem 作为字符串传递(使用“引号”)?看起来elem变量已经保存了一个字符串值,即id的名称(“status”)

如果您对此有任何见解或需要纠正的误解,我将不胜感激!

<script type="text/javascript">
function countDown(secs,elem) {
var element = document.getElementById(elem);
element.innerHTML = "Please wait for "+secs+" seconds";
if(secs < 1) {
clearTimeout(timer);
element.innerHTML = '<h2>Countdown Complete!</h2>';

}
secs--;
var timer = setTimeout('countDown('+secs+',"'+elem+'")',1000);
}
</script>
<div id="status"></div>
<script type="text/javascript">countDown(10,"status");</script>

最佳答案

Why must 'countDown('+secs+',"'+elem+'")' be passed as a string?

它不必这样传递。虽然setTimeout接受字符串,您应该避免传递字符串。当您以某种方式尝试使用对象调用回调函数时,您很快就会看到它的局限性。传递函数是一种更好的方法。

Likewise, in that same line, why must elem be passed as a string (using "quotes")? It seems that the elem variable already holds a string value, the name of the id ("status")

没错,elem已经是一个字符串,但如果省略引号,您将创建一个字符串,例如

'countDown(10, status)'

如果setTimeout稍后评估该字符串时,它将尝试访问变量 status ,它不存在。这就是为什么你希望最终的字符串看起来像

'countDown(10, "status")'

为此,您必须添加引号。

<小时/>

因此,更简洁的实现是

var timer = setTimeout(function() {
    countDown(secs, elem);
}, 1000);

请注意,该代码实际上无法正常工作。 timer变量的作用域错误,没有任何效果并且 setTimeout即使 secs < 1 仍会被调用.

大概应该是这样的:

function countDown(secs,elem) {
    var element = document.getElementById(elem);
    if(secs < 1) {
        element.innerHTML = '<h2>Countdown Complete!</h2>';
        return;
    }
    else {
         element.innerHTML = "Please wait for "+secs+" seconds";
    }
    setTimeout(function() {
        countDown(secs - 1, elem);
    }, 1000);
}

关于javascript - 将函数作为参数传递时使用字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18755931/

相关文章:

c# - 在 C# 中使用字符串拆分

swift - 关于 ..< 函数声明的说明

php - 删除 WooCommerce 评论选项卡上的 (0)

android - 将在短信中发送的超链接字符串

c - 将数组传递给 C 函数以更新结构

javascript - 有没有办法阻止 Javascript 命令在控制台中执行?

javascript - 相同条件下的多个 onclick 函数

javascript - 为什么可以将原型(prototype)的函数存储在变量中?

javascript - PHP 在单选按钮单击时显示文本框

Java:字符串填充失败