I have an up/down vote mechanism that is updated via ajax. Originally, the code in my view to display the vote count was: <p id='votes'><%= pluralize video.vote_sum, 'Vote' %></p>
and the code in my create.js.erb file was: $('selector').html("<p id='votes'><%= escape_javascript pluralize(@video.vote_sum, 'Vote') %></p>");
However, I realized I wanted to have different CSS styling for the number generated from <%= pluralize video.vote_sum, 'Vote' %>
than that for the text "Vote" or "Votes". This required me changing the view code to:
<p id='votes'>
<%= video.vote_sum %>
<div class="vote_text">
<% word = "Vote" %>
<% if video.vote_sum != 1 %>
<%= word.pluralize %>
<% else %>
<%= word %>
<% end %>
</div>
</p>
which works fine. However, when I changed the JS code to this:
$('selector').html("<p id='votes'>
<%= video.vote_sum %>
开发者_开发问答 <div class="vote_text">
<% word = "Vote" %>
<% if video.vote_sum != 1 %>
<%= word.pluralize %>
<% else %>
<%= word %>
<% end %>
</div>
</p>");
the vote display stops updating. Now voting works and all, because when I refresh the page, it displays the correct vote count with the correct styling. However, the ajax has stopped working. How can I fix this?
You have unescaped quotation marks in that JavaScript string. Also, multi-line strings in JavaScript need some special markup — a \
at the end of each non-terminating line.
Fixed:
$('selector').html("<p id='votes'> \
<%= video.vote_sum %> \
<div class=\"vote_text\"> \
<% word = "Vote" %> \
<% if video.vote_sum != 1 %> \
<%= word.pluralize %> \
<% else %> \
<%= word %> \
<% end %> \
</div> \
</p>");
$('selector').html("<p id='votes'> "+
"<%= video.vote_sum %> "+
"<div class=\"vote_text\"> "+
"<% word = "Vote" %> "+
"<% if video.vote_sum != 1 %> "+
"<%= word.pluralize %> "+
"<% else %> "+
"<%= word %> "+
"<% end %> "+
"</div> "+
"</p>");
I got this solved this way...it works fine if you use JS type join
Hope this helps
精彩评论