javascript document.getElementById().value 仅适用于数字,不适用于字符串
我有一个基于 AJAX 的应用程序,它根据用户输入更新表单中的文本字段。文本字段定义如下:
<%= form.text_field :queue, {:class => "queue_class", :id => "queue", :size => 40} %>
Javascript 代码如下:
document.getElementById('queue').value = <%= @returned_value %>
如果在控制器中,我将 @returned_value 设置为一个数字,例如:
@returned_value='77777777777'
then 就可以正常工作。但是,如果我将其设置为字符串值,例如:
@returned_value='abcxyz'
那么它不起作用,文本字段不会更新,并且我没有收到任何错误消息,就像它什么也没做一样。
我也尝试过这个:
document.getElementById('queue').innerHTML = <%= @returned_value %>
但它不适用于任何返回值,无论是在 @returned_value='77777777777'
时还是在 @returned_value='abcxyz'
时,
有人可以指点我吗我在这里想念什么?
I have an AJAX based application that updates a text field in a form depending on user input. The text field is defined as follows:
<%= form.text_field :queue, {:class => "queue_class", :id => "queue", :size => 40} %>
the Javascript code is the following:
document.getElementById('queue').value = <%= @returned_value %>
If in the controller, I set @returned_value to a number, like:
@returned_value='77777777777'
then is works fine. But if I set it to a string value like:
@returned_value='abcxyz'
then it does not work, the text field is not updated and I don't get any error message, it's like it does nothing.
I also tried this:
document.getElementById('queue').innerHTML = <%= @returned_value %>
but it does not work with any returned value, neither when @returned_value='77777777777'
nor when @returned_value='abcxyz'
Can someone please point me to what am I missing here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您缺少 ERb 表达式周围的引号:(
它也应该是 JavaScript 转义的。)
数字是不带引号的合法 JavaScript 表达式。任意字符串不是; JS 会尝试将其解析为表达式(引用)以及字符串中与 JS 相关的任何其他内容。
You're missing quotes around the ERb expression:
(And it should be JavaScript-escaped as well.)
A number is a legal JavaScript expression without quotes. Arbitrary strings aren't; JS will try to parse it as an expression (reference) plus whatever else is in the string that's relevant to JS.
javascript 代码生成为字符串,稍后由 javascript 解释器进行传递。因此,。如果生成字符串,则必须在其周围加上引号,如下所示:
The javascript code is generated as a string which is later pasred by the javascript interpreter. Thus,. if you generate strings, you have to put quotation marks around it like so:
您需要在 JavaScript 中引用字符串:
数字通过
.toString()
强制转换为字符串,但未加引号的字符串将引发解析器错误。You need to quote the string from within JavaScript:
Numbers get coerced to strings via
.toString()
, but unquoted strings will throw a parser error.