简体   繁体   English

简单的按钮即可检查JavaScript中的表单验证

[英]Simple button to check form validation in Javascript

I'm just trying to create a simple button to check if an input field is empty and style it accordingly. 我只是试图创建一个简单的按钮来检查输入字段是否为空,并相应地设置其样式。 I feel like this should be really simple but I'm just missing something. 我觉得这应该很简单,但我只是想念一些东西。

<input id="text"></input>
<button id="button">check</button>
<script>
var text = document.getElementById('text');
var button = document.getElementById('button');

function checker() {
   if (text.value === "") {
    text.style.cssText = "background:red;";
    return false;
   }
   else {
       text.style.cssText = "background:green;";
   }
}

button.addEventListener("click", checker(), false);
</script>

And here's the link to a jsfiddle that I was using to try and get it to work. 这是我用来尝试使其工作的jsfiddle的链接。

Link 链接

Instead of passing a reference to the checker() function, you are actually calling the function and passing the result. 您实际上是在调用该函数并传递结果,而不是传递对checker()函数的引用。

What you want to do is pass a reference to the function like this... 您想要做的就是传递对此类函数的引用...

button.addEventListener("click", checker, false);

Note the lack of () 注意缺少()

You need to pass the function by reference: 您需要通过引用传递函数:

button.addEventListener("click", checker, false);

Note: you could also pass an anonymous function: 注意:您还可以传递匿名函数:

button.addEventListener("click", function(){checker();}, false);

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

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