简体   繁体   English

如何在 Rails 中使用 HTML5 + JavaScript

[英]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.假设我有一个数组中的对象列表,并且我希望这些项目中的每一个都有一个 id,让我们说data-id="<%= item.id%>"我如何将这个 data-id 传入JavaScrpt 以便它显示带有项目 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:我不确定你到底在问什么,但如果你想遍历一个数组并为每个 id 显示警报,它看起来像这样:

# 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:为了解决@mikeycgto 的大量警报点,如果您只想同时拥有所有 id 的警报,您可以这样做:

<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.编辑:因此,如果您想传递 id 并将您的项目部分内部的 id 用于您的 js,您可以将渲染部分与集合一起使用。

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

This will render "items/_item.erb" and pass the local variable ad to the template for display.这将呈现“items/_item.erb”并将局部变量 ad 传递给模板进行显示。 An iteration counter will automatically be made available to the template with a name of the form partial_name_counter.迭代计数器将自动提供给模板,其名称形式为 partial_name_counter。 In the case of the example above, the template would be item_counter.在上面的例子中,模板是 item_counter。

So in your _item.erb partial you could access the item like this:因此,在您的 _item.erb 部分中,您可以像这样访问该项目:

<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.这将使用 class 项目以“item_”的形式呈现具有 div id 的块,并且 js 将写出块内的 id。 You can repurpose the js to do whatever you need.您可以重新利用 js 来做任何您需要的事情。

If you want to actually be able to use the data you should serialize it as json如果您想真正能够使用数据,您应该将其序列化为 json

How to do Ruby object serialization using JSON 如何使用 JSON 进行 Ruby object 序列化

Then just pass it to a variable然后只需将其传递给变量

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

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

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