[英]how to return clean javascript from a rails3 custom view helper?
Using Rails 3: In my update.js.erb file I found I was repeating a lot of stuff. 使用Rails 3:在我的update.js.erb文件中,我发现我在重复很多东西。 So I tried to put it all into a helper. 因此,我试图将其全部放入一个助手中。 But I'm having trouble getting the helper to give back clean javascript. 但是我很难让助手返回干净的JavaScript。 It puts in \\"
放在\\"
everywhere instead of " 无处不在,而不是“
Here's what I started with: 这是我开始的:
<% if @list.show_today %>
$("#show_today_check_<%= @list.id %>").removeClass("gray").addClass("orange").attr("value","0");
<% else %>
$("#show_today_check_<%= @list.id %>").removeClass("orange").addClass("gray").attr("value","1");
<% end %>
<% if @list.show_inventory %>
$("#show_inventory_check_<%= @list.id %>").removeClass("gray").addClass("white").attr("value","0");
<% else %>
$("#show_inventory_check_<%= @list.id %>").removeClass("white").addClass("gray").attr("value","1");
<% end %>
etc.
Here's the helper I wrote to generate the above javascript: 这是我编写的用于生成上述javascript的帮助程序:
def toggelButtonState( object, name, color)
if object.send(name)
@add_col = color
@rem_col = 'gray'
@value = "0"
else
@add_col = 'gray'
@rem_col = color
@value = "1"
end
js = '$("#'
js += "#{name}_check_#{@list.id}"
js += '").removeClass("'
js += @rem_col
js += '").addClass("'
js += @add_col
js += '").attr("value","'
js += @value
js += '");'
end
I call it with: 我称它为:
<%= toggelButtonState( @list , 'show_today', 'orange' ) %>
And here's what I get in the response: 这是我得到的答复:
$(\"#show_today_check_2\").removeClass(\"orange\").addClass(\"gray\").attr(\"value\",\"1\");
Now I did notice a similar problem with straight html in helpers. 现在我确实注意到辅助程序中直接html出现了类似的问题。 It wouldn't let me return stuff in angle brackets. 它不会让我在尖括号中返回内容。 But then I found out about content_tag. 但是后来我发现了有关content_tag的信息。 Is there something similar for javascript? javascript有类似的东西吗? How can I get rid of the \\"
如何摆脱\\"
s? S'
Add 加
js.html_safe js.html_safe
as last line of toggelButtonState function 作为toggelButtonState函数的最后一行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.