我希望我的网站上有一个以 php(来自 MySQL 数据库)的值开头的倒计时。
目前我使用以下功能:
<script type="text/javascript">
var seconds;
var temp;
var tijd = <? echo json_encode($t); ?>
function countdown() {
seconds = document.getElementById('countdown').innerHTML;
seconds = parseInt(seconds, tijd);
if (seconds == 1) {
temp = document.getElementById('countdown');
temp.innerHTML = "0";
return;
}
seconds--;
temp = document.getElementById('countdown');
temp.innerHTML = seconds;
timeoutMyOswego = setTimeout(countdown, 1000);
}
countdown();
</script>
但如果 $t 不是 10,则该值会以奇怪的步骤增加。我该如何解决这个问题?我没有 JavaScript 经验,所以这就是问题所在。
除此之外,当我添加此脚本时,以下代码:
header('Content-Type: text/html; charset=iso-8859-1');
不再起作用,因为例如“ë ”用 ? 表示在文字中。不知道为什么会这样?
谁能帮助我?提前致谢。
最佳答案
如果你想要一个人类可读的计数器,你必须在 parseInt 函数的第二个参数中使用 10
"Specify 10 for the decimal numeral system commonly used by humans."
那么您想要从数据库检索的唯一数字就是计数器的起始值。
我认为您的 HTML 代码中有这样的内容:
<div id="countdown"><?php echo $startCounterFromDB; //This is the start of the counter ?></div>
如果您想保留代码,则只需更改 JavaScript 中的 parseInt 函数的第二个参数即可。
<script type="text/javascript">
var seconds;
var temp;
var tijd = 10; //always use 10
function countdown() {
seconds = document.getElementById('countdown').innerHTML;
seconds = parseInt(seconds, tijd);
if (seconds == 1) {
temp = document.getElementById('countdown');
temp.innerHTML = "0";
return;
}
seconds--;
temp = document.getElementById('countdown');
temp.innerHTML = seconds;
timeoutMyOswego = setTimeout(countdown, 1000);
}
countdown();
</script>
最后UTF-8是所有文件的PSR标准,但你不需要使用json_encode函数,因为你只需要打印一个数字。
这段代码可以工作。
关于javascript - 倒计时 javascript 与 php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41208149/