【问题标题】:Calling CoffeeScript file for html form validation using external reference使用外部引用调用 CoffeeScript 文件进行 html 表单验证
【发布时间】:2013-07-04 08:23:29
【问题描述】:

我是 CoffeeScript 的初学者,正在做我的第一个 html 验证。 我无法验证我的 html 表单。 代码如下:

<script type="text/coffeescript">
usernameValidate = ->
  x = document.getElementById("username").value
  ptrn = /^[A-z0-9]{5,8}$/
    if ptrn.test(x)
      document.getElementById("usrmsg").innerHTML = ""
      barwidth = barwidth + 10
      document.getElementById("progress").style.width = barwidth + "%"
      return true
    else
      y = "Only Alpha Numeric and Length between 5-8 chars"
      document.getElementById("usrmsg").innerHTML = "<img src='./icons/error.png'>" + y
      document.getElementById("progress").style.width = barwidth + "%"
      document.getElementById("username").focus()
      return false
barwidth = 0
 </script>
<script type="text/javascript" src="js/coffee-script.js"></script>

和html:

<input type="text" name="uname" placeholder="User Name" id="username" onblur="usernameValidate()">
<span id="usrmsg"></span>
<div class="progress progress-striped active" id="progressbar">
<div class="bar" id="progress"></div>
</div>

我使用 twitter bootstrap 作为进度条。 我想要 - 为有效用户名增加宽度的进度条 - 如果输入不是有效模式,则应显示错误消息

请指出我哪里出错了。 提前谢谢你

【问题讨论】:

  • 您是否尝试使用 Firebug 或 Chrome 中的调试器对其进行调试?如果没有,请尝试单步执行代码,看看会发生什么。
  • 变量barwidth 似乎不合适。当我阅读代码时,它在使用之前没有被初始化。
  • 那是你真正的缩进吗?让客户端编译你的 CoffeeScript 是个坏主意,你应该在服务器端做,这样你只需要做一次。
  • @mu 太短谢谢你的建议
  • 我非常感谢任何更多的方法和建议。谢谢你:)

标签: html coffeescript


【解决方案1】:

首先修复缩进,以便拥有有效的 CoffeeScript:

usernameValidate = ->
  x = document.getElementById("username").value
  ptrn = /^[A-z0-9]{5,8}$/
  if ptrn.test(x)
    document.getElementById("usrmsg").innerHTML = ""
    barwidth = barwidth + 10
    document.getElementById("progress").style.width = barwidth + "%"
    return true
  else
    y = "Only Alpha Numeric and Length between 5-8 chars"
    document.getElementById("usrmsg").innerHTML = "<img src='./icons/error.png'>" + y
    document.getElementById("progress").style.width = barwidth + "%"
    document.getElementById("username").focus()
    return false
barwidth = 0

我会将barwidth 移动到顶部,但这并不重要,因为无论如何变量都会被提升到顶部,并且它将在usernameValidate 运行之前被初始化。

我发现另外两个可能的问题:

  1. 您的 CoffeeScript 可能会在您的 &lt;input&gt; 被查看之后被编译为浏览器的 JavaScript。
  2. &lt;script type="text/coffeescript"&gt; 可能像通常的 coffee 命令一样将所有内容包装在一个自执行函数包装器中。

第二个可以通过强制你的函数进入全局命名空间来修复:

@usernameValidate = -> ...
# or
window.usernameValidate = -> ...

@ (AKA this) 在这种情况下应该是window,所以你应该能够使用@usernameValidate

解决第一个问题需要更多的工作。您最好的选择是停止假装它是 1995 年,并放弃 onblur 属性以支持 addEventListener 或为您执行此操作的库。如果你走这条路,那么 2 就会消失,因为你可以绑定你的事件处理程序而不必污染全局命名空间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-13
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多