[英]Passing id of an object through an onclick function of jquery in Ruby On Rails
I have one Controller VendorController
. 我有一个Controller VendorController
。 And view file is index.html.erb
并且视图文件是index.html.erb
I want to pass the id of vendor through onclick function. 我想通过onclick函数传递供应商的ID。 Here is my code 这是我的代码
Codes under vendors_controller.rb
在vendors_controller.rb
下的vendors_controller.rb
def index
@vendor = Vendor.all
end
Codes of index.html.erb
index.html.erb
代码
<script language="javascript" type="text/javascript">
function func1(id) {
alert(_id);
}
function func2(id) {
alert(id);
}
</script>
<% @vendors.each do |vendor| %>
<tr>
<td><%=link_to vendor.name , '#', onclick: "func1(1)", remote: true %></td>
<td><%= link_to vendor.id, '#', :onclick => 'func2(vendor.id)' %></td>
</tr>
<% end %>
For func1()
i am getting the alert. 对于func1()
我收到警报。 But for func2
I am not getting any response. 但对于func2
我没有得到任何回应。 Please help..thank you in advance. 请帮助..提前谢谢你。
@max-williams answer should solve your problem. @ max-williams的答案应该可以解决你的问题。 But I'd also recommend that you explore the option of embedding the record ID in the <tr>
tag as a data attribute instead of writing out the onclick
function. 但我还建议您探索将记录ID作为数据属性嵌入<tr>
标记而不是写出onclick
函数的选项。 Then in your JS, you can dynamically select the ID in your event listeners. 然后在JS中,您可以在事件侦听器中动态选择ID。
Consider: 考虑:
<tr data-id="<%= vendor.id %>">
<td><%= link_to vendor.id, '#', :class=>"vendor-link" %></td>
</tr>
Then just listen for clicks: 然后只是听取点击:
$( ".vendor-link" ).click(function() {
id = $(this).closest("tr").data("id");
alert(id);
});
This method will separate out your JS from your HTML template and make it a little more manageable. 此方法将您的JS与HTML模板分开,并使其更易于管理。 Plus, you can also attach multiple click functions, giving you a little more flexibility. 此外,您还可以附加多个单击功能,为您提供更多灵活性。
I think you just need to escape the contents of your onclick to have the actual id in it, instead of just a string saying "vendor.id" - remember it's just a string, so it needs to have the right data in it when it gets loaded in the browser. 我认为你只需要逃脱onclick的内容以获得其中的实际id,而不仅仅是一个字符串“vendor.id” - 记住它只是一个字符串,因此它需要在其中包含正确的数据在浏览器中加载。
Try 尝试
<td><%= link_to vendor.id, '#', :onclick => "func2(#{vendor.id})" %></td>
Note double quotes, to allow string interpolation. 注意双引号,以允许字符串插值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.