带有倒计时变量的 Whatsapp 共享按钮

Whatsapp sharing button with a countdown variable

Web 编码的初学者,我在编写一个指向 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)尝试使用该变量时,它找不到它并发生错误。

您想从两个不同的函数访问倒计时字符串,因此一种选择是创建一个新函数来生成倒计时字符串 returns。然后您可以从这两个地方调用该函数。我在这里做到了:

<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>