我有一个使用javascript随机显示引号列表的网站。我在7-8个其他网站上使用过相同的脚本没有问题,但是在这个当前的网站上它只是在几秒钟之后就崩溃了。
我确实有一个类似的问题是由于在没有引号的页面上调用了javascript,但我通过将javascript移动到与引号相同的“包含”文件来修复此问题(意味着永远不能在没有其他的情况下召集)
该网站与另一个网站位于同一服务器空间,文件完全相同,所以我无法理解为什么这个网站出现问题而其他网站没有...
这是脚本......
<ul id="quote">
<?php perch_content('Testimonials'); ?>
</ul>
<script type="text/javascript">
this.randomtip = function() {
var pause = 5000; // define the pause for each tip (in milliseconds) Feel free to make the pause longer so users can have time to read the tips :)
var length = $("#quote li").length;
var temp = -1;
this.getRan = function() {
// get the random number
var ran = Math.floor(Math.random() * length) + 1;
return ran;
};
this.show = function() {
var ran = getRan();
// to avoid repeating tips we need to check
while (ran == temp) {
ran = getRan();
};
temp = ran;
$("#quote li").hide();
$("#quote li:nth-child(" + ran + ")").fadeIn(500);
};
// initiate the script and also set an interval
show();
setInterval(show, pause);
};
$(document).ready(function() {
randomtip();
});
</script>
先谢谢你们!
答案 0 :(得分:2)
我注意到的第一件事是你的脚本根本没有封装。在您的代码中,“this”表示窗口对象。 show和getRan函数都是window(全局)对象的成员。
您可以尝试使用此版本来完全封装变量:
$(document).ready(function () {
var pause = 5000; // define the pause for each tip (in milliseconds)
var length = $("#quote li").length;
var temp = -1;
var getRan = function() {
// get the random number
var ran = Math.floor(Math.random() * length) + 1;
return ran;
};
var show = function() {
var ran = getRan();
// to avoid repeating tips we need to check
while (ran == temp) {
ran = getRan();
};
temp = ran;
$("#quote li").hide();
$("#quote li:nth-child(" + ran + ")").fadeIn(500);
};
// initiate the script and also set an interval
show();
setInterval(show, pause);
});
答案 1 :(得分:1)
您只有一个引号,这意味着getRan()
总是会返回相同的值(1)。由于temp
设置为上一个值,因此您将获得无限循环:
var ran = getRan();
while (ran == temp) {
ran = getRan();
}
如果你将它包装在这样的安全检查中,它应该可以工作。
var ran = getRan();
if (length > 1) {
while (ran == temp) {
ran = getRan();
}
}