简体   繁体   English

为什么每次页面加载时我的脚本都不会运行?

[英]Why won't my script run every time the page loads?

Here is my current code, it's a loop to type out some text automatically when my site is loaded. 这是我当前的代码,它是一个循环,在我的网站加载时自动输出一些文本。 The issues is it is very touch and go, it only works sometimes (generally first load, not when refreshed etc.) Can someone point out the issue? 问题是它是非常触摸和去,它只有时有效(通常是第一次加载,而不是刷新等)有人可以指出问题吗?

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();

Try putting your code inside window.onload = function() {//Your code here...}; 尝试将你的代码放在window.onload = function() {//Your code here...}; It should be enough just to wrap the following: 它应该足以包装以下内容:

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();
}

The myLoop function definition should be outside the block. myLoop函数定义应该在块之外。

Try this: 尝试这个:

HTML: HTML:

<body onload="myFunction()">

Javascript: 使用Javascript:

function myFunction(){
//your code here
}

Try this: 尝试这个:

$( document ).ready(function() { 

// Your code here }); //你的代码在这里});

PS: This is JQuery though. PS:这是JQuery。

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

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