简体   繁体   English

为什么我不能使用 - 在字段名称?

[英]Why can't I use - in field names?

Basically I'm just trying to clear a text field, which has never been a problem for me. 基本上我只是想清除一个文本字段,这对我来说从来都不是问题。 However, this is NOT working: 但是,这不起作用:

<html>
<body>

<form name="form">

<input type="text" name="input-field" value="Value" />

<input type="button" name="clear" value="Clear field" onclick="document.form.input-field.value = ''"; />

</form>

</body>
</html>

But if I rename "input-field" to "inputfield" and onclick to onclick="document.form.inputfield.value = ''"; 但是,如果我将“input-field”重命名为“inputfield”并onclick to onclick =“document.form.inputfield.value =''”; ... Then it works fine. ...然后它工作正常。

However... Removing the "-" from the field name, is not an option in my case (long explanation). 但是...从字段名称中删除“ - ”,在我的情况下不是一个选项(长解释)。

So, how do I clear a text field, containing a "-"??? 那么,如何清除包含“ - ”的文本字段?

Because it's not a valid JavaScript identifier. 因为它不是有效的JavaScript标识符。 However, you can use the following instead: 但是,您可以使用以下代码:

document.form['input-field'].value

It's for the same reason you can't declare a variable using var my-var . 出于同样的原因,您无法使用var my-var声明变量。 On the other hand, if you have an object , such as form with several keys, you can access its properties as if it was an associative array: 另一方面,如果您有一个object ,例如具有多个键的form ,则可以像访问关联数组一样访问其属性:

var form = {
  "input-field": 20,
  otherKey: 30
};
form.input-field; // Error
form.otherKey; // OK
form['input-field']; // OK

References: 参考文献:

- is not a valid character in an identifier because, for example - ,不是标识符中的有效字符

document.form.input-field;

is interpreted as 被解释为

document.form.input - field;

Of course you can remedy the problem by using the square bracket notation: 当然,您可以使用方括号表示法来解决问题:

document.form["input-field"];

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

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