这是我当前的代码,它是在我的网站加载时自动输出一些文本的循环。问题是它非常触摸和去,它只在某些情况下有效(通常是第一次加载,而不是在刷新时等)。有人可以指出问题吗?
var i = 0;
var line_1 = " Understand their core goal.. Act upon the emotion..";
var line_2 = " Then..";
var line_3 = " Create your own luck!";
var all = line_1 + "{" + line_2 + "{" + line_3 + "{{";
var has = "";
var time = 100;
var hit = 0;
function myLoop () {
setTimeout(function () {
if(all.charAt(i) == "{") {
//has +1"<br>";
time = 2000;
hit++;
if(hit == 3){
document.getElementsByName('cbar')[0].placeholder = 'Enter your email address to learn more';
}
}else{
has += (all.charAt(i));
time = 100;
}
if(hit == 4){
document.getElementById('cbar').value = "";
}else{
document.getElementById('cbar').value = has;
}
if(all.charAt(i) == "{" || hit == 3){
has = "";
}
i++;
if (i < all.length) {
myLoop();
}
}, time)
}
myLoop();
答案 0 :(得分:2)
尝试将代码放在window.onload = function() {//Your code here...};
中。仅仅包装以下内容就足够了:
window.onload = function() {
var i = 0;
var line_1 = " Understand their core goal.. Act upon the emotion..";
var line_2 = " Then..";
var line_3 = " Create your own luck!";
var all = line_1 + "{" + line_2 + "{" + line_3 + "{{";
var has = "";
var time = 100;
var hit = 0;
myLoop();
}
myLoop
函数定义应该在块之外。
答案 1 :(得分:1)
试试这个:
HTML:
<body onload="myFunction()">
使用Javascript:
function myFunction(){
//your code here
}
答案 2 :(得分:0)
试试这个:
$( document ).ready(function() {
//你的代码在这里 });
PS:这是JQuery。