Javascript Rails无法正常工作
因此,我的upvote链接正在替换所有链接的投票计数器,而不是单个链接。帮忙 控制器Javascript Rails无法正常工作,javascript,ruby-on-rails,ajax,Javascript,Ruby On Rails,Ajax,因此,我的upvote链接正在替换所有链接的投票计数器,而不是单个链接。帮忙 控制器 def upcount @category = Category.find(params[:id]) @category.upcount @category.save respond_to do |format| format.html {redirect_to categories_path(@category)} format.js end
def upcount
@category = Category.find(params[:id])
@category.upcount
@category.save
respond_to do |format|
format.html {redirect_to categories_path(@category)}
format.js
end
end
查看
<% @categories.each do |category| %>
<div class="col-md-3 col-sm-6 hero-feature">
<div class="thumbnail">
<%= image_tag category.image.url(:large) %>
<div class="caption">
<%= category.name %> - <%= category.quote %></p>
<%= link_to "Upvote", upcount_category_path(category), method: "put", remote: true %>
<div id="total-votes">
<%= category.count %>
</div>
</div>
</div>
</div>
<% end %>
-
Upcount.js.erb
$("#total-votes").html("<%= @category.count %>")
$("#total-votes-<%= @category.id %>").html("<%= @category.count %>")
$(“#总票数”).html(“”)
单击第二个链接会将第一个和第二个链接替换为15。感谢您的帮助。谢谢 HTML ID应该是唯一的。重复使用“总票数”id将导致无效HTML。这也会混淆javascript,因为它不知道要将哪个div作为目标 您可以通过将类别id添加到html id(如
总投票数-
)来解决此问题,这样它对所有人都是唯一的
完整示例:
查看文件
<% @categories.each do |category| %>
<div class="col-md-3 col-sm-6 hero-feature">
<div class="thumbnail">
<%= image_tag category.image.url(:large) %>
<div class="caption">
<%= category.name %> - <%= category.quote %></p>
<%= link_to "Upvote", upcount_category_path(category), method: "put", remote: true %>
<div id="total-votes-<%= category.id %>">
<%= category.count %>
</div>
</div>
</div>
</div>
<% end %>
-
Upcount.js.erb
$("#total-votes").html("<%= @category.count %>")
$("#total-votes-<%= @category.id %>").html("<%= @category.count %>")
$(“#总票数-”).html(“”)
让我们尝试使用指向“Upvote”的链接,而不选择“remote:true”?@brian Lau我想你的up vote first和second的链接或div具有相同的id总投票数
所以这件事happened@VishalJAIN你说得对,我不知道怎么修,但幸运的是你挽救了这一天。