简体   繁体   English

如何使用嵌入式ruby动态创建jquery选择器(在.js.erb文件中)?

[英]How can I use embedded ruby to dynamically create a jquery selector (in a .js.erb file)?

As part of an ajax call, I am trying to use embedded ruby to generate the id portion of a jquery select in a .js.erb file. 作为ajax调用的一部分,我试图使用嵌入式ruby来生成.js.erb文件中的jquery选择的id部分。 Below is how I got it to work, but I had to use a slight of hand and get the javascript in the browser to concat the id to the selector instead of constructing the jquery selector on the server. 下面是我如何使它工作的方法,但是我不得不花些力气,然后在浏览器中获取javascript,以将id连接到选择器,而不是在服务器上构造jquery选择器。

$("tr.design#".concat(<%= @form_column.form_row.id.to_s %>)).html("<%= escape_javascript( render(:partial => "form_rows/row") ) %>")

I tried several combinations: 我尝试了几种组合:

$(<%= escape_javascript("tr.design#" << @form_column.form_row.id.to_s) %>)

$(<%= "tr.design#" << @form_column.form_row.id.to_s %>)

$("tr.design#<%= @form_column.form_row.id.to_s %>")

in each case the selector returned to the client was $(tr.design#17) (without quotes) and therefore was not executed as I wanted on the client, ie jquery didn't find any matches. 在每种情况下,返回给客户端的选择器都是$(tr.design#17)(不带引号),因此未按我想要的在客户端上执行,即jquery找不到任何匹配项。

The .html("<%= escape_javascript( render(:partial => "form_rows/row") ) %>") portion was sent to the browser correctly, ie the <%= ... %> behaved as expected and the javascript on the browser received nicely formatted, quoted (and escaped) html passed in the .html function. .html("<%= escape_javascript( render(:partial => "form_rows/row") ) %>")部分已正确发送到浏览器,即<%= ...%>的行为符合预期,浏览器上的javascript收到了.html函数中传递的格式良好,带引号(且转义)的html。

Anyone got any ideas on how I could avoid the use of .concat in my .js.erb file? 任何人都对如何避免在.js.erb文件中使用.concat有任何想法?

Like this 像这样

$('#user_<%= @user.id %>').click(blah blah blah);

If you place <%= %> in a js.erb file, that code is evaluated an printed in the resultant JS. 如果将<%=%>放置在js.erb文件中,则会将该代码评估为结果JS中的打印内容。 You can construct any unique string you want. 您可以构造任何所需的唯一字符串。 Probably :classname_:id is most common solution. :classname_:id可能是最常见的解决方案。

By the way, the evaluated code don't has to be an string. 顺便说一句,评估的代码不必是字符串。 <%=%> calls .to_s for printing. <%=%>调用.to_s进行打印。 In that example, the @user.id is converted into a string. 在该示例中,@ user.id被转换为字符串。

id是唯一的,您可能可以做

$("#"+<%= @form_column.form_row.id.to_s %>)

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

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