【问题标题】:Add the innerHTML of a div within erb在erb中添加一个div的innerHTML
【发布时间】:2015-07-11 12:13:30
【问题描述】:

我有一个带有用户 ID 的链接。这保存在一个名为 NameID 的 div 中。控制器等都设置正确,但我需要做的就是能够将 NameID.innerHTML (这是一个数字)作为 people.id 代表的数字传递。我该怎么做?

index.html.erb(图表未显示)

<div class="container-fluid">
    <div class="row">
          <div class="col-md-12">
          <div class="row">
                <div class="col-md-4">

                    <p><a class="btn btn-lg btn-primary" id="BtnMessageNode" href="/messages/new">Start conversation</a></p>

                <h2>NameID of Node</h2>
                <div id="NameID_Div"></div>

          </div>
    </div>
</div>
</div>
</div>

<% page_header "Users" %>


<ul>
  <% @peoples.each do |people| %>
    <li>
      <strong><%= people.name %></strong>
      <% unless current_user == people %>
        <%= link_to 'Send message', new_message_path(to: people.id), class: 'btn btn-default btn-sm' %>
      <% end %>
    </li>
  <% end %>
</ul>

messages_controller.rb

class MessagesController < ApplicationController
  before_action :authenticate_user!

  def new
    @chosen_recipient = User.find_by(id: params[:to].to_i) if params[:to]
  end

  def create
    recipients = User.where(id: params['recipients'])
    conversation = current_user.send_message(recipients, params[:message][:body], params[:message][:subject]).conversation
    flash[:success] = "Message has been sent!"
    redirect_to conversation_path(conversation)
  end
end

【问题讨论】:

  • 请粘贴您的完整代码

标签: jquery html ruby-on-rails ruby


【解决方案1】:

我认为没有一种简单的方法可以将您的NameID.innerHTML 嵌入 ERB。所以我建议改用一些自定义 jQuery。首先,在您的链接中添加一个 id:

<%= link_to 'Send message', new_message_path(to: people.id), id: 'sendMessage', class: 'btn btn-default btn-sm' %>

然后在你的脚本中使用 jQuery:

$("#sendMessage").click(function(e){
  e.preventDefault();
  var nameId = $("#NameID_Div").html();
  // Then just assign the proper URL of the new_message_path with the proper NameID
  location.assign('/message/' + nameId + '/new');
});

【讨论】:

  • 嗨,阿布拉尔。代码不起作用。我认为 sendmessage 输出需要代替 people.id。 people.id 仅定义为来自控制器的 @peoples 变量的循环的一部分。如果我可以将 jquery 结果放在这里,那么我根本不需要使用 people 变量。如何放置 jquery 输出,使其作为 to: 参数的一部分传递?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-16
  • 2013-12-28
  • 2019-03-29
相关资源
最近更新 更多