gpt4 book ai didi

将函数链接到单击按钮的 Javascript

转载 作者:行者123 更新时间:2023-11-30 11:14:06 24 4
gpt4 key购买 nike

我要通过单击按钮来调用计时器。定时器函数:

function countDown(seconds, elem){
var element = document.getElementById(elem);
element.innerHTML = "Please wait for "+seconds+ " seconds";

if(seconds < 1){
clearTimeout(timer);
element.innerHTML ='<h2> You can let Go, Frist Responders have been informed</h2>';
}
seconds--;

var timer = setTimeout('countDown('+seconds+',"'+elem+'")',1000);
}

函数调用:

document.querySelector('body').onClick = countDown(5,"para");

HTML:

<div class="wrapper" id="butt2">
<button id="butt" class="fade-in-fwd" >SOS</button>
</div>

<p id="para"></p>

这会在网页加载后立即开始运行计时器。我如何限制这个

最佳答案

您的代码中有几个问题:

  1. onClick应该写成onclick
  2. onclick 需要一个将在点击时触发的函数。由于您在 onclick 中分配了 countDown(5,"para"),它会立即被调用。

document.querySelector('body').onclick = function(){
countDown(5,"para");
}
function countDown(seconds, elem) {
var element = document.getElementById(elem);
element.innerHTML = "Please wait for " + seconds + " seconds";

if (seconds < 1) {
clearTimeout(timer);
element.innerHTML = '<h2> You can let Go, Frist Responders have been informed</h2>';
}
seconds--;

var timer = setTimeout('countDown(' + seconds + ',"' + elem + '")', 1000);
}
<div class="wrapper" id="butt2">
<button id="butt" class="fade-in-fwd">SOS</button>
</div>

<p id="para"></p>

Note that there will be weird behaviour with this code if you click multiple times as timer is reinitialized without clearing the previous one so you need to handle that too.

关于将函数链接到单击按钮的 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52342735/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com