简体   繁体   English

CSS输入改变并恢复正常

[英]CSS input change and return to normal

I tried to make a warning if the input is not the same , like the example below: 如果输入不相同,我试图发出警告,如下例所示:

 $data = document.getElementById("target").value = ""; $("#target").keyup(function() { if ($data.length > 3) { $("#target").css("border-color", "red"); }; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <input id="target" class="form-control" type="text" value=""> </form> 

But it did not work, so if true then the border-color has to change 但它不起作用,所以如果是真的那么边框颜色必须改变

You need to move your $data variable into inside keyup events. 您需要将$data变量移动到内部keyup事件中。 Since you've add jQuery tag, I've selecting object using jQuery method too. 既然你已经添加了jQuery标签,我也会使用jQuery方法选择对象。


UPDATE UPDATE

  • Simplify the code 简化代码

 $("#target").keyup(function(){ var $data = $("#target").val(); $("#target" ).css("border-color", $data.length > 3 ? "red" : ""); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <input id="target" class="form-control" type="text" value=""> </form> 

In provided example, $data holds "" (empty string) 在提供的示例中, $data保存"" (空字符串)

In event-handler-function , this refers to the element on which event is invoked hence this.value will return the value of the element. event-handler-functionthis引用调用事件的元素,因此this.value将返回元素的value

 var $data = $("#target"); $data.val(''); $data.keyup(function() { if (this.value.length > 3) { $("#target").css("border-color", "red"); } else { $("#target").css("border-color", ""); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <input id="target" class="form-control" type="text" value=""> </form> 

Another approach I would like to suggest is to using jQuery.toggleClass instead of jQuery.css 我想建议的另一种方法是使用jQuery.toggleClass而不是jQuery.css

 var $data = $("#target"); $data.keyup(function() { $("#target").toggleClass('error', this.value.length > 3); }); 
 .error { border-color: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <input id="target" class="form-control" type="text" value=""> </form> 

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

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