【发布时间】:2017-03-30 16:56:33
【问题描述】:
所以,我有部分表格行和不同的表格数据在哪里。通过单击一个按钮(位于<tr> 中),我发送Ajax 请求(简单地说,使用remote: true)并使用操作更新项目数据(显示在<tr> 中)。
一切正常,但我无法将接收到的数据从 Ajax 发送到特定的<td>。如果显示更多项目 - 所有项目都会收到该数据。
_partial.html.erb:
<body>
<div>
<tr data-line-item-id='<%= line_item.id %>' class='line-item'>
<td data-th="Product">
<div class="row">
<div class="col-sm-2 hidden-xs"></div>
<div class="col-sm-10">
</div>
</div>
</td>
<td data-th="Price"><%= number_to_currency(line_item.product.price) %></td>
<td data-th="Quantity">
<%= line_item.quantity %>
</td>
<td data-th="Subtotal" class="text-center" class="subtotal">
<%= number_to_currency(line_item.total_price, :unit => "€", separator: ",", format: "%n %u") %></td>
<td class="actions" data-th="">
<td><%= link_to "-", decrease_line_item_path(product_id: line_item.product), remote: true %></td>
<td><%= link_to "+", increase_line_item_path(product_id: line_item.product), remote: true %></td>
</td>
</tr>
</div>
</body>
减少.js.erb:
$("td[data-th='Quantity']").html('<%= @line_item.quantity %>');
我的“不错的尝试”是这样的:
$(this).parent().parent().find("td[data-th='Quantity']").html('<%= @line_item.quantity %>');
但我的“最好的成就”是只更新特定的,按数字项找到,如下所示:
$("td[data-th='Quantity']").eq(0).html('<%= @line_item.quantity %>');
否则它们都会更新...
更新
这,有点让它工作,但如果我增加一个项目的数量然后增加其他项目的数量,首先单击显示先前更新的项目编号的数量......但答案很接近。希望有人可以帮助...非常感谢
增加.js.erb:
$(document).ready(function(){
$('.increase').click(function(){
var element = $(this).parent().parent()
$(element).find("td[data-th='Quantity']").html('<%= @line_item.quantity %>');
});
});
【问题讨论】:
-
您想通过单击同一行中的 +/- 按钮单独增加/减少该行中的项目数?
-
是的。但这已经完成。现在我担心的是为什么当我增加或减少一个项目的数量,然后单击另一个项目上的增加/减少按钮时,第一次单击会显示先前增加或减少的项目数(第二次单击代表正确的数字)。我假设它与 Ajax 请求有关,例如该数据仍存储在流中。我对 Ajax 完全陌生,所以现在尝试阅读并理解一些东西
-
$('.increase'),你是在increase.js.erb或decrease.js.erb写的吗? -
是的,我更新了我的问题以显示哪个代码代表
increase.js.erb
标签: javascript jquery html ruby-on-rails ajax