使用jQuery时如何在循环中识别哈希元素 [英] How to identify hash elements in a loop when using jquery
问题描述
我有以下哈希(@messages),它们是按发件人/发件人分组的消息:
I have the following hash (@messages) which are messages grouped by sender/from:
{'Tom'=>[#<ShortMessage id: 16, content: "ABC", created_at: "2014-01-28 16:35:33", from: 'Tom'>, #<ShortMessage id: 15, content: "DEF", created_at: "2014-01-28 13:11:20", from: 'Tom'>], 'Jerry'=>[#<ShortMessage id: 5, content: "XYZ", created_at: "2014-01-22 09:48:52", from: 'Jerry'>]}
在我看来,我遍历散列以打印出发件人姓名及其消息组.我还为每组邮件提供了一个表格,用户可以在其中答复特定的发件人
In my view I loop through the hash to print out the senders name and their group of messages. I've also got a form for each group of messages where the user can reply to that particular sender
<% @messages.each do |sender, message| %>
<p><%= sender %></p>
<% message.each do |msg| %>
<p><%= msg.content %></p>
<% end %>
// reply form
<%= form_for @message, remote: true do |f| %>
<%= f.hidden_field :from, value: from %>
<%= f.text_field :content %>
<%= f.submit "Reply" %>
<% end %>
<% end %>
我正在使用ajax和jquery提交表单并将新的回复文本添加到消息组的末尾,因此不必每次发送回复时都刷新页面
I'm using ajax and jquery to submit the form and add the new reply text to the end of the group of messages so the page doesn't have to refresh every time a reply is sent
在遍历哈希时,如何引用附加新回复的消息组中的哪一个?
How do I reference which one of the groups of messages to append the new reply to when looping through the hash?
例如,如果我想回复汤姆并填写他的回复表格,我该如何附加到那组消息而不是杰里的消息上?
Example if I want to reply to Tom and fill out his reply form how do I append to that group of messages and not Jerry's?
我失败的jquery看起来像这样:
My unsuccessful jquery looks something like this:
<script>
$('#container').on('ajax:success', function(event, data){
if (data.succ) {
// handle your success somehow, like show a new field
} else {
// something went wrong
}
})
</script>
推荐答案
我可能会将ajax:success
绑定到表单本身而不是#container
上(这不在问题中).然后,t就像
I would probably bind ajax:success
to a form itself rather than #container
(which is not in the question btw). Then t is as simple as
$(this).before(...)
这篇关于使用jQuery时如何在循环中识别哈希元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!