[英]Ruby on Rails: link_to javascript
<% @services.each do |service| %>
<div class="widget-content nopadding">
<ul class="activity-list">
<li>
<%= link_to service.company.name, "#", :id => 'specific_service' %>
</li>
</ul>
</div>
<% end %>
So, I have a list of various services which all have an id. 因此,我列出了所有具有ID的各种服务。 the link_to displays the service's company name which performs the 'specific_service' javascript function.
link_to显示执行“ specific_service” javascript函数的服务公司名称。 But I want it to display unique data according to the service's id.
但是我希望它根据服务的ID显示唯一数据。 How do I pass in the service.id to the link_to in order for the controller to have access to the correct service?
如何将service.id传递给link_to,以使控制器可以访问正确的服务?
EDIT 编辑
$('#specific_service').click(function(){
var id = $(this).data('id');
var _url = '<%= dashboard_specific_service_path(:format => :js) %>?start_date=' + encodeURI($('#start_date').val()) + '&end_date=' + encodeURI($('#end_date').val()) + '&service_id=' + id;
$.ajax({
type: 'GET',
url: _url,
dataType : 'script'
});
});
This is my javascript function which invokes a file called 'specific_service.js.erb' which would then render a partial called 'specific_service'. 这是我的javascript函数,它调用一个名为“ specific_service.js.erb”的文件,然后将渲染一个名为“ specific_service”的部分文件。 The thing is I don't know if I'm using the var id correctly.
问题是我不知道我是否正确使用了var id。
You can use data-
attributes to pass arbitrary values to a HTML element: 您可以使用
data-
attribute属性将任意值传递给HTML元素:
link_to service.company.name, # e.g. "ACME"
'#',
:class => 'specific_service',
:data => {:id => service.id} # e.g. 12345
which will result in something like this: 这将导致如下所示:
<a href="#" class="specific_service" data-id="12345">ACME</a>
this can be retrieved inside the Javascript, eg with jQuery: 可以在Javascript中进行检索,例如使用jQuery:
$('.specific_service').click(function() {
var id = $(this).data('id');
// now do something with the id
});
note that i used :class
not :id
because the element can occur multiple times. 请注意,我使用了
:class
而不是:id
因为该元素可以出现多次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.