简体   繁体   English

如何阻止警报框自行关闭?

[英]how do i stop alert box from closing out itself?

 document.getElementById("error").style.display = "none"; document.getElementById("submit").onclick = function() { document.getElementById("error").style.display = ""; }
 .alert-er { padding: 20px; background-color: #ff2400; color: #ffffff; font-size: 20px; border: 1px solid white; border-radius: 20px; }.closebtn { margin-left: 15px; color: white; font-weight: bolder; float: right; font-size: 40px; line-height: 20px; cursor: pointer; transition: 0.3s; }.closebtn:hover { color: black; }
 <div id="error" class="alert-er"> <span class="closebtn" onclick="this.parentElement.style.display='none';">&times;</span> <strong>Error!</strong> </div> <form> <button type="submit" id="submit" class="submit">Submit</button> </form>

a tried to display a alert box showing error and it worked fine until i changed display properties. a 试图显示一个显示错误的警告框,并且在我更改显示属性之前它工作正常。 now it appears and then disappears automatically in less than a second.现在它出现,然后在不到一秒钟的时间内自动消失。 i tried cheking for errors.我试着检查错误。 i changed codes different times using css, js and jquery.我使用 css、js 和 jquery 更改了不同时间的代码。 but in all of those cases happened the same.但在所有这些情况下,情况都是一样的。 please do care to help.请注意帮助。

Try using尝试使用

type="button"

in

<button type="button" id="submit" class="submit">Submit</button></form>

<div id="error" class="alert-er">
    <span class="closebtn" onclick="this.parentElement.style.display='none';">&times;</span> 
    <strong>Error!</strong> 
</div>  
<form>
    <button type="button" id="submit" class="submit">Submit</button>
</form>

The problem is that when you click the submit button, the form is being submitted.问题是当您单击提交按钮时,表单正在被提交。

To fix this, let's create an event listener for when the form is submitting.为了解决这个问题,让我们为表单提交时创建一个事件监听器。 If we find an error, we don't let it continue the submission, and show the error message instead.如果我们发现错误,我们不会让它继续提交,而是显示错误消息。 We do this with the help of event.preventDefault():我们在 event.preventDefault() 的帮助下做到这一点:

const form = document.querySelector('form');
const errorMessage = document.getElementById("error");

form.addEventListener('submit', (event) => {

  if(thereIsAnError()){
    event.preventDefault();
    errorMessage.style.display = "block";
  }

})

function thereIsAnError(){
    return true; // later, change this function to return true or false depending on your input values
}

document.getElementById("error").style.display = "none";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM