<from>
<input type="number" placeholder="time interval" id="time">
<input type="submit" id="submit" value="start">
</form>
<br>
<br>
<audio src="p.mp3" controls="controls" id="audio">
Your browser does not support the audio tag.
</audio>
<script type="text/javascript">
(function(){
var music = document.getElementById('audio');
var submit = document.getElementById('submit');
//1
var mytime = document.getElementById('time').value*60000;
function musicStart(){
music.play();
};
submit.addEventListener('click',function(){
//2, var mytime=document.getElementById('time').value*60000;
if(music.paused === true){
setTimeout(musicStart, mytime);
//music.play();
}else{
//time.value ="";
music.pause();
}
})
}());
</script>
上面的脚本,当我把代码var mytime = document.getElementById('time').value*60000;
放在1位时,它不能起作用但在2位起作用?
mytime
变量(在function(){}
中定义)应该在嵌套函数中访问(在嵌套函数中定义)。
当我将mytime变量放在1位时,为什么它不起作用?帮助
答案 0 :(得分:4)
当您加载页面时,它会运行脚本,此时&#34; time&#34;输入为空,因此mytime
的值将为空。
当你将它放在click事件中时,当你运行click时,它只会获取值,这将为你提供结果。
答案 1 :(得分:0)
尝试在父函数中声明变量,然后在嵌套函数中初始化它:
<script type="text/javascript">
(function(){
var music = document.getElementById('audio');
var submit = document.getElementById('submit');
var mytime;
function musicStart(){ music.play(); };
submit.addEventListener('click',function(){
mytime=document.getElementById('time').value*60000;
if(music.paused === true){
setTimeout(musicStart, mytime);
//music.play();
}else{
//time.value ="";
music.pause();
}
})
}());
</script>