我在点击提交时尝试调用timedText()
函数,而不是调用setTimeout()
并用1秒,2秒和3秒替换标记<p>
。
<script>
function timedText()
{
var x=document.getElementById('txt1');
var t1 = setTimeout(function(){x.innerHTML="1 seconds"},1000);
var t2 = setTimeout(function(){x.innerHTML="2 seconds"},2000);
var t3 = setTimeout(function(){x.innerHTML="3 seconds"},3000);
}
</script>
<p>
<a href="#">
Izmeni<p id="txt1"></p>
</a>
</p>
<input type="submit" name="answer" value="Postavi" onclick="timedText()"/>
答案 0 :(得分:0)
有些事情发生了变化:
<强>的jsfiddle 强>
<强> HTML 强>
<p>
<a href="#">Izmeni</a>
<p id="txt1"></p>
</p>
<input type="button" id="button" name="answer" value="Postavi" />
<强> JS 强>
function timedText(){
var x=document.getElementById('txt1');
var t1=setTimeout(function(){x.innerHTML="1 seconds"},1000);
var t2=setTimeout(function(){x.innerHTML="2 seconds"},2000);
var t3=setTimeout(function(){x.innerHTML="3 seconds"},3000);
}
document.getElementById('button').addEventListener('click',timedText);
答案 1 :(得分:0)
这是因为提交按钮正在提交页面。
就个人而言,我喜欢使用<button onclick="dosomething()">Click me!</button>
。但是有些浏览器也把它视为提交按钮...所以请确保你在事件处理程序中return false;
(即。onclick="dosomething(); return false;"
)
答案 2 :(得分:0)
也许这会帮助您更清楚地看待事物(希望如此):
<p><a href="#">Izmeni<p id="txt1"></p></a></p>
<input type="submit" name="answer" value="Postavi" onclick="StartTimer(3)"/>
<script type="text/javascript">
var timerId = null;
var element = document.getElementById("txt1");
function StartTimer(numOfSeconds)
{
element.innerHTML = String(numOfSeconds)+" seconds";
timerId = setInterval(TimerIsr,1000);
}
function StopTimer()
{
clearInterval(timerId);
element.innerHTML = "";
}
function TimerIsr()
{
var numOfSeconds = Number(element.innerHTML.split(" ")[0]);
if (numOfSeconds > 2)
element.innerHTML = String(numOfSeconds-1)+" seconds";
else if (numOfSeconds == 2)
element.innerHTML = "1 second";
else
StopTimer();
}
</script>