Javascript 如何在动态生成的Rails表上创建JS函数
我试图创建一个JS函数来增加页面上的投票计数,这通常是通过编写Javascript 如何在动态生成的Rails表上创建JS函数,javascript,ruby-on-rails,Javascript,Ruby On Rails,我试图创建一个JS函数来增加页面上的投票计数,这通常是通过编写Document.getElementByID然后写入ID来实现的,但在Rails中,我试图找出如何编写这个函数,在循环中动态创建表行。我将如何创建一个函数来执行此操作 以下是html rails循环: <tbody> <% @requests.each do |request| %> <tr> <td><%= request.artist
Document.getElementByID
然后写入ID来实现的,但在Rails中,我试图找出如何编写这个函数,在循环中动态创建表行。我将如何创建一个函数来执行此操作
以下是html rails循环:
<tbody>
<% @requests.each do |request| %>
<tr>
<td><%= request.artist %></td>
<td><%= request.title %></td>
<td><%= request.voteCount %></td>
<td><button onclick="upVote()">Vote</button></td>
</tr>
<% end %>
</tbody>
投票
您有几个选项:如果您想继续使用onclick处理程序,只需将请求ID传递给upVote()函数即可。可能是这样的:
<td><button onclick="upVote(<%= request.id %>)">Vote</button></td>
请注意,我使用的是POST方法,因为具有副作用的操作不应该通过GET请求完成。确保你的路线相应
然后在RequestsController中:
def upvote
request = Request.find(params[:id])
request.upvote! # Or do whatever you need to do to upvote it
# Respond to your JS request with whatever updated info it might need to update the UI
render json: { voteCount: request.voteCount } }
end
最后,在JS中(以CoffeeScript编写):
在您提到的第一种方法中,如何获取元素以进行更新?这是我的JS代码
函数upVote(requestID){var count=document.getElementsByClassName(“voteCount”)[0]。innerHTML;count=parseInt(count);count=count+1;count=count.toString();document.getElementById(“voteCount”)。innerHTML=count;document.getElementById(“voteButton”)。禁用=“true”;}
一个选项是将数据请求id属性添加到,例如:
。然后在JS中,您可以使用$(“tr[data request id='“+requestID+”])再次找到它
。但我强烈建议您使用rails ujs方法。我想尝试rails方法,但我是rails的新手,我想我在实现它时会遇到更困难的问题。我尝试了一下,发现一个错误未定义的方法
upvote\u request\u path',html是'Vote'“你需要为你的投票操作添加一条路线。请查看路线指南。一般来说,Rails指南是你的朋友。它们写得非常好,信息量也非常丰富——我鼓励任何刚接触Rails的人至少浏览一下,以了解各种组件是如何组合在一起的。
def upvote
request = Request.find(params[:id])
request.upvote! # Or do whatever you need to do to upvote it
# Respond to your JS request with whatever updated info it might need to update the UI
render json: { voteCount: request.voteCount } }
end
$('a.upvote').on 'ajax:success', (event) ->
# Update your UI to reflect the upvote (you can access the JSON returned from your upvote action here to make necessary updates)