- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我正在尝试向我的页面添加打字机效果,它可以很好地处理预定义数据,但我无法将其转换为接收值然后打印这些值的函数。
我尝试通过添加参数来更改原始函数并尝试打印传入的值,但只打印了第一个字母。
<-- 这是原始函数。 -->
let i = 0;
let txt = 'Hello world';
let speed = 50;
function typeWriter() {
if (i < txt.length) {
document.getElementById("text").innerHTML +=
txt.charAt(i);
i++;
setTimeout(typeWriter, speed);
}
}
typeWriter();
<-- 这是我把它改成的。 -->
function typeWriter(id, text) {
if (i < text.length) {
document.getElementById(id).innerHTML += text.charAt(i);
i++;
setTimeout(typeWriter, speed);
}
}
typeWriter("text", "Hello world" );
打印第一个字母,控制台打印这条消息“error”“类型错误:无法读取未定义的属性‘长度’ 在 typeWriter (xifoxoj.js:18:16)”
我的预期值是传递给函数的文本值将完全打印在带有传递给函数的 id 的元素中,而不是只打印文本值的第一个字母。
最佳答案
使用 String#split、Array#forEach。
注意:按speed * i
增加速度
function typeWriter(id, text) {
const speed = 500;
const ele = document.getElementById(id)
text.split("").forEach((c,i)=>{
setTimeout(()=>{
ele.innerHTML += c;
}, speed*i);
});
}
typeWriter("text", "Hello world");
<div id="text"></div>
关于javascript - 如何把这个函数变成干函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54344309/
我的主函数中有这两个函数。正如您将看到的,它们两者之间的唯一区别在于它们附加/编辑 html 的方式。我认为最好提出两个新函数,一个执行前半部分,另一个执行后半部分。我不确定这是否可以用 jQuery
我是编码新手,但一直在阅读有关 DRY - 不要重复自己的内容。 我有一个不适合 DRY 方法的 JavaScript if/else 语句,但我无法练习如何编写 JavaScript if/else
我的情况很简单: $("#check-in").dateDropper({ years_multiple: "10", format: "d-m-Y", minYear: "2
我想要一个方法在很多地方创建以下 json 字符串: {"daily_calendar":{"search":{"print_date":"2014-06-30"}}} 我有以下四行代码来制作散列:
我有这个正则表达式来检查字符串的格式是否为date, two or three dots ,date /\A(\d{1,2}-\d{1,2}-\d{4})...?(\d{1,2}-\d{1,2}-\d
我正在试验一些代码来创建我自己的 DOM 方法,但没有扩展实际的 DOM,类似于 jQuery 的工作方式。到目前为止,这是我的原型(prototype): function Lib( selecto
我是 Java 编程的新手。这里有人可以帮我让我的代码保持干燥吗? Button level01 = (Button) findViewById(R.id.level01); level01.setO
我正在通过一个数组来根据外部设置的状态应用不同的类。这就是我现在的做法,但我觉得我在重复自己很多次。有干燥机的方法吗?如果有帮助,类名可以是其他名称。 var children2 = Array.fr
关闭。这个问题需要details or clarity .它目前不接受答案。 想改进这个问题吗? 通过 editing this post 添加细节并澄清问题. 关闭 4 年前。 Improve t
我正在尝试构建一个搜索页面,使用户能够找到满足特定阈值标准的模型的任何实例,并且在避免严重冗余代码方面遇到困难。我希望有更好的方法来做到这一点。这是一个稍微做作的示例,应该说明我正在尝试做什么,并在最
我是一名优秀的程序员,十分优秀!