简体   繁体   中英

how to use HTML5 + JavaScript in Rails

Lets assume I have a list of objects in an array and i want each of those items to have an id, let us say data-id="<%= item.id%>" how can i pass this data-id in in JavaScrpt so that it displays an alert message with the items id.

I'm not sure exactly what you are asking, but if you want to iterate over an array and display alerts for each id it would look something like this:

# assuming @items is and array of objects
<% for item in @items %>
  <script>alert('<%= item.id %>')</script>
<% end %>

To address @mikeycgto's point of a ton of alerts, if you wanted to just have an alert with all the id's at once, you could do:

<script>alert('<%= @items.collect(&:id) %>')</script>

EDIT: So if you want to pass the id along and use the id inside of your item partial for your js, you can use render partial with a collection.

render :partial => 'item', :collection => @items

This will render "items/_item.erb" and pass the local variable ad to the template for display. An iteration counter will automatically be made available to the template with a name of the form partial_name_counter. In the case of the example above, the template would be item_counter.

So in your _item.erb partial you could access the item like this:

<div id="item_<%= #{item.id} %>" class="item">
  <script>document.write('this is my item id written from JS: <%= item.id %>');</script>
</div>

This would render blocks with div ids in the form of "item_" with a class item, and the js would write out the id inside the block. You can repurpose the js to do whatever you need.

If you want to actually be able to use the data you should serialize it as json

How to do Ruby object serialization using JSON

Then just pass it to a variable

<script type="text/javascript">
  var json = <%= json_serialized_object %>
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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