带有文本框的jQuery .trim()
在我发表的另一篇文章中,一些人解释说,要在文本框和文本中检查空白值,请使用.val()带有$ .trim来检查空白值。例如,
if($.trim($("#textboxid").val()) == "") {
//do something
}
有人可以向我解释为什么我们需要在这里修剪任何东西?文本框中是否有隐藏的空间或马车返回?
In a different post I made, someome explained that to check for blank values in text boxes and textareas you should use .val() with $.trim to check for blank values. For e.g.,
if($.trim($("#textboxid").val()) == "") {
//do something
}
Can someone explain to me why we need to trim anything here? Are there hidden spaces or carriage returns in textboxes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
与JavaScript中的许多内容(以及一般编程)一样,这一切都是关于编写 robust 和可维护代码。该代码对错误用户输入更容易耐受。如果用户在其中放置一个空间,然后忘记了它,则在视觉上他们将无法分辨。这将通过检查您的字段是否仅包含空格来解决这种情况。
但是,在所有情况下都不适用!
此外,只要我们谈论“健壮且可维护的”代码,请确保使用明确的等效性运算符,而不是真实/假测试:
As with lots of things in JavaScript (and programming in general), it's all about writing robust and maintainable code. This code is simply more tolerant of errant user input. If a user puts a space in there and then forgets about it, visually they won't be able to tell. This will take care of that scenario by checking to see if your field contains merely whitespace.
However, it might not be appropriate in all scenarios!
Further, as long as we're talking "robust and maintainable" code, be sure to use explicit equivalency operators rather than truthy/falsey tests:
修剪的目的是,如果用户输入空格,它不会将其视为值。使用trim 使
" "
的值变为""
。trim is so that if the user put in a space, it doesn't treat it like a value. Using trim with make a value of
" "
become""
.是否要修剪文本框,这是应用特定于应用程序的。通常,很难看到,因此很难检测到。
It is application-specific whether someone wants to trim the textboxes or not. In general it is hard to see and hence detect.