在下面的代码中,我希望变量计数器在每次重复时增加1,但它保持为零。
var count = 0;
var marqueeText = new Array("Some text goes here",
"A bit more verbose text goes here.",
"Some more verbose <a href='xxx'>text</a> goes <a href='xxx'>here</a> with some <a href='xxx'>links</a>."
);
function fnShowMarquee(count){
// console.log(count + "-" + marqueeText.length );
if (count > marqueeText.length){
count = 0;
}
else{
count++;
}
$('#marquee_box span').html(marqueeText[count]);
// do some stuff, then wait 4 seconds and call function again
setTimeout ("fnShowMarquee(count)", 4000);
}
$(document).ready(function() {
fnShowMarquee(0);
});
答案 0 :(得分:3)
问题是您正在使用全局count
,然后在fnShowMarquee
中创建新的本地
请改为尝试:
var count = 0;
//...
function fnShowMarquee(){
//...
setTimeout (fnShowMarquee, 4000);
}
$(document).ready(function() {
fnShowMarquee();
});
编辑: - 来自RobG的评论:
$(document).ready(function() {
var count = 0;
//...
function fnShowMarquee(){ ... }
fnShowMarquee();
});
通过将所有内容放入ready函数中,count变量无法被其他代码访问,并且它不会在window
全局范围内乱七八糟。
答案 1 :(得分:2)
继詹姆斯回答之后,在闭包中保留 count 和 marqueeText ,这样就不会被其他代码弄乱:
var fnShowMarquee = (function() {
var count = 0;
var marqueeText = [
"Some text goes here",
"A bit more verbose text goes here.",
"Some more verbose <a href='xxx'>text</a>" +
" goes <a href='xxx'>here</a> with some <a href='xxx'>links</a>."
];
// ...
return function() {
//...
setTimeout (fnShowMarquee, 4000);
}
}());
答案 2 :(得分:1)
我尝试明确使用count
:
setTimeout (function() { fnShowMarquee(count); }, 4000);
答案 3 :(得分:1)
对您的代码进行了一些更改:
您的代码应为:
var count = 0;
var marqueeText = new Array("Some text goes here",
"A bit more verbose text goes here.",
"Some more verbose <a href='xxx'>text</a> goes <a href='xxx'>here</a> with some <a href='xxx'>links</a>."
);
function fnShowMarquee(){
console.log(count + "-" + marqueeText.length );
if (count == marqueeText.length - 1){
count = 0;
}
else{
count++;
}
$('span#marquee_box').html(marqueeText[count]);
// do some stuff, then wait 4 seconds and call function again
setTimeout ("fnShowMarquee()", 4000);
}
$(document).ready(function() {
fnShowMarquee();
});
答案 4 :(得分:-1)
您正在增加参数变量计数。不是全球性的。像这样的setTimeout使用全局的,因为它在文档范围上运行你的函数。
尝试将您的功能称为
function fnShowMarquee()
或者像
一样setTimeout (function() { fnShowMarquee(count); }, 4000);