简体   繁体   English

从Rails视图向javascript传递数据?

[英]pass data to javascript from rails view?

I am having trouble with passing the correct data from my rails html.erb view file to my js file. 我在将正确的数据从Rails html.erb视图文件传递到js文件时遇到麻烦。

I have the following in my controller (@messages = Message.all) and in my html.erb view file: 我在控制器(@messages = Message.all)和html.erb视图文件中具有以下内容:

@messages.each do |x|
x.name
end

if i have a javscript file how do i pass the id of the specific message to it? 如果我有一个javscript文件,如何将特定消息的ID传递给它?

I am trying this: 我正在尝试:

@messages.each do |x|
<span id="messageid" data-id="<%= x.id %>">
 <%=x.name%>
</span>
end

and in my javascript file: 并在我的javascript文件中:

$("#messageemail").click(function(){
  var messageid = $("#messageemail").data('id');
alert(messageid);

this partially works, but it only gives me the id for the first message in the list. 这部分起作用,但是它只给我列表中第一条消息的ID。 I want it to give me the specific id of which ever message is clicked 我希望它给我单击邮件的具体ID

Do this instead, add a class to your span element instead of id 改为执行此操作,将一个class (而不是id添加到您的span元素中

<span class="message-class" data-id="<%= x.id %>">

In Javascript file 在Javascript文件中

$(".message-class").on('click', function(){
  var messageid = $(this).attr("data-id");
  alert(messageid);
});

This will work! 这将起作用!

In your rails view: 在您的rails视图中:

<span  onclick="callJS(<%= x.id %>)">
 <%=x.name%>
</span>

Here on clicking the span the callJS function will be called. 在单击范围时,将调用callJS函数。

in the js : 在js中:

// in your js file
 function callJS(x_id){
  console.log(x_id);
}

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

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