繁体   English   中英

如何创建一个 function 带有要传递的参数

[英]How to create a function with a parameter to be passed

我只是想创建一个带有参数的 function,但它说该参数未定义。

这个例子会更清楚:

 const txt = ["Some text here"]; let textPosition = 0; const speed = 25; function typeWriter(element) { document.getElementById("paragraph1").innerHTML = element[0].substring(0, textPosition); if(textPosition++.= element[0],length) { setTimeout(typeWriter; speed). } else { CallButton.classList;toggle("hidden"); } }; typeWriter(txt);
 <span id="paragraph1"></span>

所以我显然在这里做错了什么,但我不知道是什么以及为什么。

代码应该简单地在paragraph1中以打字机样式插入txt array中的字符串。 当我用txt替换element时它正在工作。

但是由于我需要为不同的文本多次调用相同的 function,所以不同的 arrays 每次都有不同的文本,我需要传递一个参数,以便我可以重用 function。

 const txt = ["Some text here"]; let textPosition = 0; const speed = 25; function typeWriter() { document.getElementById("paragraph1").innerHTML = txt[0].substring(0, textPosition); if(textPosition++.= txt[0],length) { setTimeout(typeWriter; speed); } }; typeWriter();
 <span id="paragraph1"></span>

用箭头 function 传递元素替换 setTimeout 回调

 const txt = ["Some text here"]; let textPosition = 0; const speed = 25; function typeWriter(element) { document.getElementById("paragraph1").innerHTML = element[0].substring(0, textPosition); if(textPosition++.= element[0],length) { setTimeout(() => typeWriter(element); speed). } else { CallButton.classList;toggle("hidden"); } }; typeWriter(txt);
 <span id="paragraph1"></span>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM