0

我尝试将 jquery popover 添加到 rails 默认 cruds 而不是重定向到视图,我正在做的是在 jquery popover 中呈现表单:

<%= content_tag_for :tr, @order.order_items do |i| %>
<a class='btn btn-mini label-with-popover' id=<%=i.id%>><%= t('helpers.links.edit_html') %> </a>
<% end %>    

<script type="text/javascript">
    $(function () {
      $('.label-with-popover').popover({ 
        html : true,
        content: "<%= escape_javascript(render :partial => 'form_item') %>" , 
        placement:  'top'
      } );
    });
    </script>

这是我的form_item:

<%= simple_form_for :order_item, url:  admin_shop_order_path,  :html => { :class => 'form-horizontal' } do |f| %>
  <div class='form-inputs'>
    <%= f.input :item_id , :collection => @shop.products.collect{|b| b.variants}.flatten.map{|variant| ["#{variant_full_title(variant)}", variant.id]}%> 
    <%= f.input :quantity %>
  </div>
  <div class="form-actions">
    <%= f.button :submit, :class => 'btn-primary' %>
    <%= link_to t("helpers.links.cancel"), admin_shop_orders_path, :class => 'btn' %>
  </div>
<% end %>

但问题出现在编辑按钮上。要呈现编辑表单,我们需要我们想要编辑的对象(我的意思是:order_item),而获得它的方法是使用 id,这就是我设置锚标签 id 的原因。现在我们必须在 popover 函数中获取那个锚 id,但是 $(this).id 不起作用。有什么建议吗?

4

2 回答 2

1

我认为你渲染错误,你应该尝试用当地人渲染你的部分。您还可以将局部变量传递给局部变量,使它们更加强大和灵活。

在您的情况下,在渲染您的部分form_item脚本标记时,您可以这样编写:

<script type="text/javascript">
    $(function () {
      $('.label-with-popover').popover({ 
        html : true,
        content: "<%= escape_javascript(render :partial => 'form_item', :locals => {order_item: @order_item}) %>" , 
        placement:  'top'
      } );
    });
    </script>

并在您的表单中,您将能够像这样访问它:

<%= form_for(order_item) do %>

 # write your form stuff %>

<% end %>

通过这种方式,您可以处理表单以进行创建或编辑操作。

首先,我建议您传递 id 并添加一些文本(我将 id 替换为"link_<%= i.id%>"). 其次在您的 a 标签上调用 onclick 函数:

<%= content_tag_for :tr, @order.order_items do |i| %>
<a class='btn btn-mini label-with-popover' id="link_<%=i.id%>" ><%= t('helpers.links.edit_html') onclick="javascript:openPopup(this.id)" %> </a>
<% end %>   

最后但并非最不重要的一点是,在您的函数中获取 id,并将其传递给您的部分。

<script type="text/javascript">
    function openPopup(a_id) {
      var id = a_id.split("link_")[1];
      $('.label-with-popover').popover({ 
        html : true,
        content: "<%= escape_javascript(render :partial => 'form_item', locals => {:id => id}) %>" , 
        placement:  'top'
      } );
    });
    </script>

我不擅长 javascript,但是从我的回答中,您会得到我想向您解释的内容。我相信你会找到一种更好的方法来做到这一点。如果你这样做,也请在这里发布。希望它会有所帮助。谢谢

于 2013-07-28T13:42:51.453 回答
1

在 jQuery 中,您需要使用 attr('id') 来获取元素的 id。尝试将 $(this).id 替换为:

$(this).attr('id')

有关详细信息,请参阅 jQuery 的文档:http: //api.jquery.com/attr/

但实现这一点的首选方法通常是使用数据属性。这是将数据从视图传递到某些 JS 代码的一种干净的方式。您的链接如下所示:

<a class='btn btn-mini label-with-popover' data-item-id=<%=i.id%>>...</a>

在您的 JS 文件中,您将使用以下方法获得此值:

$(this).data('item-id')

jQuery 的文档:http ://api.jquery.com/data/

于 2013-07-28T13:29:09.307 回答