php - 带有倒计时变量的 Whatsapp 共享按钮
问题描述
网络编码初学者,我有问题编写一个共享按钮,该按钮导致whatsapp并共享倒计时。我用静态字符串实现它,但我无法在其中加载变量......
请问有人知道我的问题在哪里吗?
<script>
// Set the date we're counting down to
var countDownDate = new Date("Aug 20, 2022 12:00:00").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
var countdown_iam = days + "j " + hours + "h "
+ minutes + "m " + seconds + "s "
// Output the result in an element with id="countdown"
document.getElementById("countdown").innerHTML = countdown_iam;
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("countdown").innerHTML = "SURPRISE!!!";
}
}, 1000);
function openWhatsApp() {
//var countdown_whatsapp = "test";
//alert(countdown_iam);
window.open('whatsapp://send?text=' + countdown_iam);
}
</script>
<h2> WhatsApp sharing Link </h2>
<!-- create an image icon to open the WhatsApp onclick -->
<img src="img/whatsapp.png" height="50" size="50" onclick="openWhatsApp()">
谢谢你的帮助
解决方案
countdown_iam
变量是在函数中创建的,并且只存在于该函数中。所以当另一个函数(openWhatsApp
)试图使用该变量时,它找不到它并发生错误。
您想从两个不同的函数访问倒计时字符串,因此一种选择是创建一个新函数来生成倒计时字符串并返回它。然后,您可以从两个地方调用该函数。我在这里做到了:
<script>
function getCountdown() {
var countdownDate = new Date("Aug 20, 2022 12:00:00").getTime();
var now = new Date().getTime();
var distance = (countdownDate - now) / 1000;
if (distance < 0) {
return 'SURPRISE!!!';
} else {
var days = Math.floor(distance / (60 * 60 * 24));
var hours = Math.floor((distance % (60 * 60 * 24)) / (60 * 60));
var minutes = Math.floor((distance % (60 * 60)) / 60);
var seconds = Math.floor(distance % 60);
return days + "j " + hours + "h " + minutes + "m " + seconds + "s ";
}
}
function openWhatsApp() {
alert('whatsapp://send?text=' + getCountdown());
}
setInterval(function() {
document.getElementById("countdown").innerHTML = getCountdown();
}, 1000);
</script>
<h2>WhatsApp Sharing Link</h2>
<p id="countdown"></p>
<p><img src="img/whatsapp.png" height="50" size="50" onclick="openWhatsApp()"></p>
推荐阅读
- python - 从文件中提取 json 对象
- linux - 为什么 AWS 实例只有 16GB 时,`/proc/meminfo` 显示 32GB?
- activemq-artemis - Artemis 对称集群示例
- magento - 如何在 Magento 2 中集中日志
- hyperledger - 我们如何在 Hyperledger Indy 钱包中导入外部创建的密钥对?
- spring-boot - Junit 5 与 Mockito java.lang.NoSuchMethodError org.junit.platform.engine.EngineDiscoveryRequest.getDiscoveryListener()
- pandas - 无法向空数据框添加新值
- spring-mvc - 在多个 spring mvc 应用程序之间共享地图数据的最佳方法是什么?
- javascript - 在异步函数中使用 Promise
- blazor - Blazor 客户端站点稳定发布日期是什么时候