开发者

Passing RoR value into javascript (JQuery) in a view

开发者 https://www.devze.com 2023-03-27 18:42 出处:网络
I\'ve been puzzled by the following code. Could someone tell me what I\'m doing wrong that javascript fails to access the value p ? Thanks !

I've been puzzled by the following code. Could someone tell me what I'm doing wrong that javascript fails to access the value p ? Thanks !

<% p=progress_for(contest_score) %> # p is non-zero

<script type="text/javascript">
  $(function(){
      $('#contest_progressbar').progressbar({value: <%=p%>}); 
      <!--value p becomes 0 when rendered by jquery-->

      $("#contest_progressbar").css({ 'background': 'LightYellow' });
      $("#contest_progressbar > div").css({ 'background': 'Orange' });
      $('#contest_progressbar span.text').text(<%=p%>+'%')
      &l开发者_如何学Got;!--value p becomes 0 when rendered by jquery-->

   });
</script>
progress: <%=p%> progress bar should be below: # p is the correct value here

<div id='contest_progressbar' style="margin-left:20px; height: 20px;">
  <span class="text"></span>
</div>

EDIT: Using straight script tag instead. Same problem though EDIT2: Seems to be a JQuery problem now. See the html in the comment to Bryan's answer


Is it possible that jQuery just isn't loading? If you check in your debugger, it might give you a hint, something like $ is not defined. If there's a Prototype/jQuery conflict (highly possible if you're using Rails before v3.1), it may fail silently.

It may also be the case that JS code block needs to appear after you've loaded jQuery. The reason I'm thinking this is the issue is that, given the information you've provided, something like $('#contest_progressbar span.text').text(5+'%'); should always work if you have jQuery loaded correctly and no other elements with the ID contest_progressbar.

Example: http://jsfiddle.net/6JQNe/1/

Also, a few minor points:

  • You need <%= javascript_tag do %> (note the equals sign) to make sure it renders.
  • "#contest_progressbar > div" will not match anything


Problem fixed. It had nothing too do with JQuery. The div id for the progressbar was clobbered because the code is in a partial, which is called by a view method in a loop. Every calls keep overwriting the same div. The code below produces the result I want.

<% pbar_id="pbar_#{contest_score.user_id}" %>

<script type="text/javascript">
  $$(function(){
      $$('#'+"<%=pbar_id%>").progressbar({'value':<%=p%>})
      $$('#'+"<%=pbar_id%>").css({ 'background':'LightYellow' });
      $$('#'+"<%=pbar_id%>"+' > div').css({ 'background':'Orange' });
   });
 </script>
progress: <%=p%>%
<div id=<%=pbar_id%> style="margin-left:20px; width:256px; height:20px;">
</div>
0

精彩评论

暂无评论...
验证码 换一张
取 消