我有一个简单的文件上传页面,其中的消息每隔一段时间显示在底部,因此我使用setInterval进行延迟。
以下功能应该仅在单击“上传”按钮后才能启动,但是该功能在页面加载后即开始执行(这不是项目的登录页面)。
我该如何编写它以便它不会在页面加载时开始执行,而是仅在单击“上载”按钮时才执行?
这是包括脚本的完整html代码:
我的研究还没有提出与页面加载与按钮单击执行直接相关的任何内容。我发现了相反的情况(希望它在页面加载时执行,而不是单击按钮),但不是这样。我根本不希望它仅在单击按钮时在页面加载时执行。
var myVar = setInterval(myTimer, 1000);
var counter = 0;
function myTimer() {
counter++;
var t = counter;
document.getElementById("td1").innerHTML = t;
if (counter >= 4) {
console.log("REACHED THE END!!");
clearInterval(myVar);
}
}
<div class="header_upload" style="margin-left: 14%">File Upload</div>
<br><br><br><br>
<div class="upload_text" style="margin-left: 6%;">
<div class="upload-btn-wrapper">
<button class="btn">Select file</button>
<input type="file" name="fileToUpload" />
</div>
</div>
<br><br>
<div class="upload_text" style="margin-left: 10%;">
<button class="btn" id="submit_btn" type="submit" value="Submit" onClick="myTimer()">Upload</button></div>
<br><br><br><br>
<div class="upload_text" style="margin-left: 6%;">
<div id="td1" class="text_display">* Step 1</div>
<div id="td2" class="text_display">* Step 2</div>
<div id="td3" class="text_display">* Step 3</div>
<div id="td4" class="text_display">* Step 4</div>
</div>
<br><br><br><br>
<div id="td7" class="text_display" style="color:rgb(175,222,162); font-size: 13pt; margin-left: 8%;">Finished</div>
<br>
答案 0 :(得分:3)
只需将事件监听器添加到按钮:
var myVar, counter; // global vars
document.getElementById("submit_btn").addEventListener("click", function() {
counter = 0;
myVar = setInterval(myTimer, 1000);
});
function myTimer() {
counter++;
var t = counter;
document.getElementById("td1").innerHTML = t;
if (counter >= 4) {
console.log("REACHED THE END!!");
clearInterval(myVar);
}
}
<div class="header_upload" style="margin-left: 14%">File Upload</div>
<br><br><br><br>
<div class="upload_text" style="margin-left: 6%;">
<div class="upload-btn-wrapper">
<button class="btn">Select file</button>
<input type="file" name="fileToUpload" />
</div>
</div>
<br><br>
<div class="upload_text" style="margin-left: 10%;">
<button class="btn" id="submit_btn" type="submit" value="Submit" onClick="myTimer()">Upload</button></div>
<br><br><br><br>
<div class="upload_text" style="margin-left: 6%;">
<div id="td1" class="text_display">* Step 1</div>
<div id="td2" class="text_display">* Step 2</div>
<div id="td3" class="text_display">* Step 3</div>
<div id="td4" class="text_display">* Step 4</div>
</div>
<br><br><br><br>
<div id="td7" class="text_display" style="color:rgb(175,222,162); font-size: 13pt; margin-left: 8%;">Finished</div>
<br>