jQuery如果/ else条件在js.erb文件中不能正常工作

时间:2014-01-17 06:53:15

标签: javascript jquery ruby-on-rails

我遇到了jQuery的问题,如果/ else条件在这里。 我在两个条件中执行渲染部分,当我通过放置调试器进行检查时,无论条件如何都执行这些条件。 并且即使条件为真,也会每次更新部分来自else条件。

2 个答案:

答案 0 :(得分:1)

<% if @associated_goal.present? %>
    <% goal_status = @associated_goal.completion_percentage(@required_tasks) %>
    var progress_bar_selector = "#cjs_show_goal_progress_bar_<%=@associated_goal.id.to_s%>";
    var progress_from_goals = "#cjs_show_goal_progress_from_goals_<%=@associated_goal.id.to_s%>";
    var goal_progress_display = ".cjs-mentoring-model-goal-progress-<%=@associated_goal.id.to_s%>";

if(progress_bar_selector != "")
      {
       $(progress_bar_selector).html("<%= escape_javascript(render :partial => "mentoring_model/goals/display_goal_progress", locals: { goal: @associated_goal, goal_status: goal_status, connection_and_reports_page: true }) %>");

    var percentage_content = <% content_tag(:span, goal_status.to_s+"%", :class => "pull-right cjs-mentoring-model-goal-progress-#{@associated_goal.id}") %>;
      jQuery(goal_progress_display).replaceWith(percentage_content);
    }
    else
    {
       $(progress_from_goals).html("<%= escape_javascript(render :partial => "mentoring_model/goals/display_goal_progress.html.erb", locals: {goal: @associated_goal, goal_status: goal_status}) %>");
    }
  <% end %>

答案 1 :(得分:0)

这是帮助我解决问题的最终解决方案。

  <% if @associated_goal.present? %>
    <% goal_status = @associated_goal.completion_percentage(@required_tasks) %>
    var progress_bar_selector = jQuery("#cjs_show_goal_progress_bar_<%=@associated_goal.id.to_s%>");
    var progress_from_goals = jQuery("#cjs_show_goal_progress_from_goals_<%=@associated_goal.id.to_s%>");
    var goal_progress_display = jQuery(".cjs-mentoring-model-goal-progress-<%=@associated_goal.id.to_s%>");
    if(progress_bar_selector.length > 0){
      progress_bar_selector.replaceWith("<%= j(render :partial => "mentoring_model/goals/display_goal_progress", locals: { goal: @associated_goal, goal_status: goal_status, connection_and_reports_page: true }) %>");
      <% percentage_content = content_tag(:span, goal_status.to_s+"%", :class => "pull-right cjs-mentoring-model-goal-progress-#{@associated_goal.id}") %>
      goal_progress_display.replaceWith("<%= j(percentage_content) %>");
    }
    else{
      progress_from_goals.replaceWith("<%= j(render :partial => "mentoring_model/goals/display_goal_progress.html.erb", locals: {goal: @associated_goal, goal_status: goal_status}) %>")
    }
  <% end %>