您如何在香草javascript中而不是在jQuery中做类似的事情?
答案 0 :(得分:1)
无法创建摘要,因为stackoverlow不允许访问localStorage,但:
<form onsubmit="handleSubmit(event)">
<input type="text" id="target" />
<input type="submit" value="submit"/>
</form>
<script>
let disable = localStorage.getItem("disable");
if(disable){
console.log("5 second timeout");
setTimeout(()=> {
localStorage.removeItem("disable");
disable = false;
console.log("button enabled");
},5000);
}
function handleSubmit(e) {
e.preventDefault();
if(disable){
console.log("button is disabled");
return;
}
localStorage.setItem("disable",true);
location.reload();
}
</script>
编辑:类似以下内容的内容可以针对特定按钮进行修改
function handlerWrapper(e) {
e.preventDefault();
if(disable){
console.log("button is disabled");
return;
}
yourActualHandler(e);
localStorage.setItem("disable",true);
location.reload();
}
答案 1 :(得分:0)
除了您提到的localStorage
API之外,您所需要的只是按钮上的disabled
属性和窗口对象上的setTimeout
方法。
有关详细说明,请参见代码中的注释。
(注意:由于使用沙箱,使用localStorage
的代码无法在SO代码段中运行,但是如果您希望看到它运行,则可以将其另存为html文件。)
<button id="refresh">Refresh</button>
<script>
const refreshBtn = document.getElementById("refresh");
refreshBtn.addEventListener("click", refresh);
disable();
function disable() {
// If `disableRefresh` is truthy...
if (localStorage.getItem("disableRefresh")) {
// ...Disables the button and re-enables it after 2 seconds
refreshBtn.setAttribute("disabled", ""); // Any value makes it true
setTimeout(enable, 2000); // JavaScript measures times in milliseconds
}
}
function enable() {
// Removes (boolean) `disabled` attribute and (string) `disableRefresh` item
refreshBtn.removeAttribute("disabled");
localStorage.removeItem("disableRefresh")
}
function refresh() {
// Sets `disableRefresh` to a truthy value, and refreshes the page
localStorage.setItem("disableRefresh", "yep");
location = location;
};
</script>