简体   繁体   English

如何通过jQuery传递ID来呈现部分内容?

[英]how to render a partial by passing an id through jQuery?

I feel really dumb and ashamed. 我感到非常愚蠢和羞愧。 Just started learning jQuery and got stuck at the first day. 刚开始学习jQuery并在第一天就陷入困境。 Basically, I am building all of this in ruby on rails, and I have a list of clients with basic info like name, address, phone number, etc. In the picture below is my page layout (yes, I know.. born artist). 基本上,我是在Rails上用ruby构建所有这些功能,并且有一个包含名称,地址,电话号码等基本信息的客户列表。下图是我的页面布局(是的,我知道..天生的艺术家)。

在此处输入图片说明

In the left table, I display all the clients I have in database, first column represents client's id and the second column shows their names. 在左表中,显示数据库中拥有的所有客户端,第一列表示客户端的ID,第二列显示其名称。 In the right table (it is a partial), I display full client's info. 在右边的表中(部分显示),我显示了完整的客户信息。 My objective is this: by clicking on the row, on the left table, the right table would update and show the info related to that client I selected. 我的目标是:通过单击左侧表中的行,右侧表将更新并显示与我选择的客户端相关的信息。 Here is what I tried : 这是我尝试的

<script>
$('#table_clients tbody').on('click', 'tr', function() {
   $("#container_info").replaceWith(
      '<%= j render :partial  => "client_info", :locals =>  {:client => 1} %>'
   );
});
</script>

Notice that I manually specified the client's ID. 请注意,我手动指定了客户端的ID。 My question is, how can I identify which row I selected and pass the ID to the erb fragment ? 我的问题是,如何确定我选择的哪一行并将ID传递给erb片段?

I can get the ID by calling this: 我可以通过以下方式获取ID:

$(this).find(':nth-child(0)').text();

But dont know how to pass it inside erb fragment. 但是不知道如何在erb片段中传递它。 What is the work around for this ? 解决该问题的方法是什么? There are probably a better way than using replaceWith method, it was the first idea I got. 可能有比使用replaceWith方法更好的方法,这是我首先想到的。

One solution is to do an ajax request to the backend fetching the partial in question. 一种解决方案是对后端进行ajax请求,以获取有问题的部分。

Controller: app/controllers/clients_controller.rb 控制器: app/controllers/clients_controller.rb

class ClientsController < ApplicationController
  #
  # GET /clients/:id/info
  #
  def info
    render partial: "client_info", locals: { client: params[:id] }
  end
end

Route: config/routes.rb 路线: config/routes.rb

resources :clients do
  member do
    get :info
  end
end

View: app/clients/index.html.erb 查看: app/clients/index.html.erb

<ul>
  <% @clients.each do |client| %>
    <li class="click" data-client-url="<%= info_client_path client.id %>">
      Click me <%= client.id %>
    </li>
  <% end %>
</ul>

<div class="side-panel">
  Waiting for data
</div>

Javascript: app/assets/javascripts/application.js Javascript: app/assets/javascripts/application.js

$(function(){
  $(".click").click(function(){
    $(".side-panel").load($(this).get("client-url"));
  });
});

It will load the url from the li element into the sidebar. 它将把来自li元素的URL加载到侧边栏中。 You just have to adjust the code to your controller and view to get it to work. 您只需要调整控制器的代码并查看即可使用。

You can get the clicked tr's first td's innerText var id = $(e.currentTarget).children().first()[0].innerText; 您可以获取被点击的tr的第一个td的innerText var id = $(e.currentTarget).children().first()[0].innerText; but you need to take the event in the callback like $('#table_clients tbody').on('click', 'tr', function(e) { 但是您需要像$('#table_clients tbody').on('click', 'tr', function(e) {

Full js fiddle: https://jsfiddle.net/dattaproffs/788tkheh/ 完整的JS小提琴: https : //jsfiddle.net/dattaproffs/788tkheh/

But i'm not sure how this will work, maybe i misunderstand but isn't the '<%= j render :partial => "client_info", :locals => {:client => 1} %>' rendered on the server? 但是我不确定这将如何工作,也许我误会了,但是不是'<%= j render :partial => "client_info", :locals => {:client => 1} %>'呈现在服务器?

When your starting out with javascript avoid falling for the temptation of mixing javascript and whatever server side language you are using. 当您开始使用javascript时,请避免陷入将javascript和您使用的任何服务器端语言混合的诱惑。

You end up with an overcomplicated mess and tons of confusion about what is happening where. 您最终会变得过于混乱,并且对在哪里发生的事情感到困惑。 Its a pretty common misstake and there is no reason to feel ashamed. 这是很常见的错误,没有理由感到羞耻。

Using AJAX as suggested by Oleander is a good alternative - but another classic way to setup sliders or tabs is by using ancor links. Oleander建议使用AJAX是一个不错的选择-但是设置滑块选项卡的另一种经典方法是使用ancor链接。

So first lets setup the table: 因此,首先让我们设置表:

<table id="table_clients">
  <thead>
   <tr>
     <td>id</td>
     <td>name</td>
   </tr>
  </thead>
  <tbody>
    <%= clients.each do |client| %>
      <tr>
        <td>
          <%= client.id %>
        </td>
        <td>
          <%= content_tag :a, client.name, href: "client-<%= client.id %>" %>
        </td>
      </tr>
    <% end %>
  </tbody>
</table>

Note the a <%= content_tag :a, client.name, href: "client-<%= client.id %>" %> part. 请注意a <%= content_tag :a, client.name, href: "client-<%= client.id %>" %>部分。 This will render something like: 这将呈现如下内容:

<a href="#client-1">Acme Corp.</a>

So lets create the details on the right side: 因此,让我们在右侧创建详细信息:

<% if clients.any %>
<ul id="client-details">
  <%= clients.each do |client| %>
  <li id="client-<%= client-id %>">
    <%= client.details # or whatever %>
  </li>
  <% end %>
</ul>
<% end %>

Even without javascript the browser will now jump down to the linked tab. 即使没有javascript,浏览器现在也会跳至链接的标签。 Progress! 进展!

So now lets enhance the behavior with javascript: 现在让我们使用javascript增强行为:

// hide everything but the first
$('#client-details li').not(':first').hide();

$('#table_clients').on('click', 'tr,a', function() {
  var id, target;

  // we don't know if the user clicked a link or a row
  if (this.tagName === 'A') {
    id = this.href;
  } else {
    id = $(this).find('a').attr('href'); 
  }

  // since the href is equal to the id we can use it as a selector
  target = $(id);
  target.show(); // show the target
  $('#client-details li').not(target).hide(); // hide the others
  return false; // prevents the view from jumping if the user clicked a link
});

Note that this is a special keyword in javascript that changes meaning depending on the concept. 请注意, this是javascript中的特殊关键字,它会根据概念更改含义。 When you attach a click handler it is the element that the user clicked. 当您附加点击处理程序时,它就是用户单击的元素。 $(this) gives us a new jQuery object with that element as the context. $(this)给我们一个新的jQuery对象,以该元素为上下文。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM