【问题标题】:Passing text in HTML element through link_to通过 link_to 传递 HTML 元素中的文本
【发布时间】:2011-08-01 23:22:06
【问题描述】:

我正在处理一个显示公司结构的页面(职位类的索引视图),它是职位的无序列表。

单击某个位置时,文本变为白色,我希望在单击“新位置”链接时将该位置的名称或 ID 传递给控制器​​。

我尝试将隐藏段落设置为包含所选位置的名称,但后来我不知道如何访问 link_to 中的段落。

有什么建议吗?代码如下:

<ul>
  <% @positions.each do |position| %>
    <% indent = "text-indent:" + ((position.depth_level - 1) * 20).to_s + "px;" %>
    <li style=<%=indent%> class="position_item"><%= position.name %></li>
  <% end %>
</ul>

<p id="selected_position" class="hide"></p>

<%= link_to 'New Position', new_position_path %>

<script>
  $("li").click(function () {
    $("li").removeClass("hilite"),
    $(this).addClass("hilite"),
    $("#selected_position").text($(this).text());
  });
</script>

【问题讨论】:

    标签: jquery html ruby-on-rails ruby views


    【解决方案1】:

    如果您希望将其传递给控制器​​,则需要使用表单(或者您也可以使用 jQuery ajax() 调用)。此外,您应该只使用一个隐藏字段来临时存储位置值,因为这可能是更合适的方式。

    <ul>
      <% @positions.each do |position| %>
        <% indent = "text-indent:" + ((position.depth_level - 1) * 20).to_s + "px;" %>
        <li style=<%=indent%> class="position_item"><%= position.name %></li>
      <% end %>
    </ul>
    
    <% form_tag(new_position_path, :id => "new_position", :method => "GET") do %>
      <input name='selected_position' type='hidden' value='' /> 
      <input name='commit' type='submit' value='New Position' />
    <% end %>
    
      <script>
        $("li").click(function () {
          $("li").removeClass("hilite"),
          $(this).addClass("hilite"),
          $("input[name='selected_position']").val($(this).text());
        });
      </script>
    

    按下提交按钮时,selected_position 参数将在表单中传递,并在控制器中以param[:selected_position] 的形式提供

    希望有帮助!

    【讨论】:

      猜你喜欢
      • 2016-05-18
      • 1970-01-01
      • 2021-03-13
      • 2017-11-09
      • 2011-12-18
      • 1970-01-01
      • 2012-10-17
      • 2011-11-16
      • 1970-01-01
      相关资源
      最近更新 更多