【问题标题】:Accessing HTML input fields with javascript - spaces in input name使用 javascript 访问 HTML 输入字段 - 输入名称中的空格
【发布时间】:2011-11-07 15:02:14
【问题描述】:

我正在向表单添加一些 javascript 验证。该表单的字段当前如下所示:

<input name="Employee Full Name" value="" type="text" id="Employee Full Name" size="30" maxlength="50" style="width:300px;">

我正在尝试访问字段的值,但我似乎在输入名称中的空格不正确,有没有办法逃脱?

if (theForm.Employee Full Name.value == ""){   
   alert("Please enter a value for the \"Employee Full Name\" field.");     
   theForm.Employee Full Name.focus();   
   return (false);   
}

【问题讨论】:

  • 请只使用下划线或其他任何东西,您可以避免很多麻烦和不立即显现的错误,并且没有额外的努力或缺点。 :( 这适用于任何属性(id 也是如此)
  • 我同意您的 cmets,但是,我没有被批准更改表单上的元素名称。 :(
  • camelCaseIsYourFriend.

标签: javascript


【解决方案1】:

您可以对对象和数组使用括号表示法:

theForm['Employee Full Name'].value == ""

这允许您访问名称在 . 表示法语法中无效的属性:

foo.1 //foo['1']
foo.this-is-wrong //foo['this-is-wrong']
foo.bar.baz //although this looks correct, it's wrong if you actually wanted foo['bar.baz']

【讨论】:

    【解决方案2】:

    使用引号将它们包含在方括号内。

    if (theForm["Employee Full Name"]value == ""){   
       alert("Please enter a value for the \"Employee Full Name\" field.");     
       theForm.["Employee Full Name"].focus();   
       return false;
    }
    

    每个 JavaScript 对象也可以通过这种方式引用。例如,以下所有方法都有相同的结果:

    window.location.href
    window["location"].href
    window.location["href"]
    window["location"]['href'] //Single quotes / double quotes don't matter.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-11
      • 2012-03-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多