以为我把它放在包里......猜我错了:
预期的行为 - 页面加载,然后对于数组中的每个元素,它使用setTimeout更新我的innerHTML值
观察到的行为 - 在我的托管上它似乎只更新了一次值,然后它在没有响应之前打破了我的CSS。我发出警告,看看它是否曾在jsFiddle上运行,而且似乎不正在运行,所以那里也是
标记:
<button type="button" id="ctaButton" class="cta btn btn-lg btn-success pulsate" data-keyboard="true" data-toggle="modal" data-target="#contactUs">Get Started Today</button>
JS:
$(warmup());
function warmup(){
//sanity check
confirm("working???");
setTimeout(changeCTAtext, 3000);
}
function changeCTAtext(){
var ctaList = [ 'Complementary Quotes', 'Book Your Consultation', 'Get Started Today' ];
var myField = document.getElementById("ctaButton");
while (true){
for (var i = 0; i<ctaList.length, i++;){
setTimeout('myField.innerHTML = ctaList[i];', 1000);
};
};
};
这是通常要求的强制性 fiddle。
答案 0 :(得分:1)
绝对不需要在循环内设置同步多个超时
仅使用一个setInterval
或召回一个功能而不是一个setTimeout
setInterval()
如果你想让你的代码更简单(没有迭代计数器),你可以像以下一样操纵数组:
jQuery(function($){
var $btn = $("#ctaButton"),
ctaList = ['Get Started Today', 'Complementary Quotes', 'Book Your Consultation'];
function changeCTAtext(){
ctaList.push( ctaList.shift() ); // manipulate
$btn.html( ctaList[0] ); // and use always the [0]th index
};
setInterval(changeCTAtext, 1000); // Start
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="ctaButton">Get Started Today</button>
c
计数器并使用++c % array.length
jQuery(function($){
var $btn = $("#ctaButton"),
ctaList = ['Get Started Today', 'Complementary Quotes', 'Book Your Consultation'],
tot = ctaList.length,
c = 0; // iterations counter
function changeCTAtext(){
$btn.html( ctaList[++c%tot] );
};
setInterval(changeCTAtext, 1000); // Start
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="ctaButton">Get Started Today</button>
使用setTimeout()
就像这样:
jQuery(function($){
var $btn = $("#ctaButton"),
ctaList = ['Get Started Today', 'Complementary Quotes', 'Book Your Consultation'],
tot = ctaList.length,
c = 0; // iterations counter
function changeCTAtext(){
$btn.html( ctaList[c++%tot] );
setTimeout(changeCTAtext, 1000); // ...and repeat every NNNms
};
changeCTAtext(); // Start
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="ctaButton">Get Started Today</button>
答案 1 :(得分:1)
我在你的代码中发现了两个错误:
setTimeout
第一个参数应该是一个函数。所以应该写成如下 setTimeout(changeCTAtext, 3000);
和
while (true){
for (var i = 0; i < ctaList.length; i++){
setTimeout(function(){myField.innerHTML = ctaList[i]}, 1000);
};
};
for (var i=0; i < ctaList.length; i++) {
(setTimeout(function(i) {myField.innerHTML = ctaList[i]}, 1000)(i);
}