简体   繁体   English

使用Javascript变量存储<%=%>中的Ruby输出

[英]Using Javascript variables to store Ruby Output from <%= %>

@tag is a string. @tag是一个字符串。

Why does this work: 为什么这样做:

tag_tracker = "<%= @tag %>";
alert(tag_tracker);

But not this? 但是不是吗?

tag_tracker = <%= @tag %>; // Why is this not read as a string?
alert(tag_tracker);

Thank you in advance! 先感谢您!

If you have JS inside of ERB files, you need to ensure that the javacript code that is generated is correct. 如果ERB文件中包含JS,则需要确保生成的javacript代码正确无误。

Let's assume that you have a string "div" stored in @tag 假设您有一个字符串"div"存储在@tag

The first option: 第一种选择:

tag_tracker = "<%= @tag %>";
alert(tag_tracker);

will generate a correct JS with div wrapped in quotes.: 会生成一个正确的JS,并用div将引号引起来:

tag_tracker = "div";
alert(tag_tracker);

The second one: 第二个:

tag_tracker = <%= @tag %>;
alert(tag_tracker);

will generate JS without quotes around the div : 将在div周围生成不带引号的JS:

tag_tracker = div;
alert(tag_tracker);

and that is incorrect, because in this case div is interpreted as a variable, not as string. 那是不正确的,因为在这种情况下div被解释为变量,而不是字符串。

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

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