Hello,我的代码中有简单的问题,我把自己作为一个用户,让我们假设如果用户单击空格按钮(在键盘上),那么解决方案是什么。
这里我的简单代码:
var name = $('input#name').val(); // get the value of the input field
if(name == "" || name == " ") {
$('#err-name').fadeIn('slow'); // show the error message
error = true; // change the error state to true
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
发布于 2017-03-12 18:53:43
使用$.trim函数移除空格
var name = $.trim( $('input#name').val() ); // get the value of the input field
if(name == "") {
$('#err-name').fadeIn('slow'); // show the error message
error = true; // change the error state to true
}发布于 2017-03-12 18:53:51
.trim函数在JavaScript中删除前导和尾随空格/新行。因此,如果用户只是垃圾邮件栏,name.trim()将删除所有前导/尾随空格,从而产生"“和”等于“。因此,您的错误代码将显示。
var name = $('input#name').val(); // get the value of the input field
if(name.trim() == "") {
$('#err-name').fadeIn('slow'); // show the error message
error = true; // change the error state to true
}https://stackoverflow.com/questions/42751647
复制相似问题