2

我在铁轨上很n00b。问题很简单,我想知道如何在 onLoad 事件的 body 标记内进行 javascript 函数调用。

我问这个是因为在视图中我找不到任何身体或头部标签(就像它们是在其他地方生成的一样)。

谢谢

4

3 回答 3

4

You do not need to modify the body tag to associate a Javascript function with onload. Instead of using the onload attribute on the body, you can assign the function to window.onload inside an external Javascript file.

There are more advanced ways, using event listeners to do the same thing (trigger the function on page load) which would allow to add several listener functions or trigger functions on DOM ready, a little/some time before page load. Just setting window.onload is the most simple way, and will keep your Javascript unobtrusive.

于 2009-11-26T21:07:20.190 回答
2

Eric Bréchemier 和 mtyaka 都是正确的。

另一种方法(如果您需要将自定义元素添加到基于每个视图指定的页眉/页脚,您将希望使用 yield 块执行类似的操作

这是一个允许在每页基础上覆盖标题的示例,但同样的技术适用script于在 HTML 头标签中设置标签。

app/views/layouts/posts_layout.html.erb

<html>
  <head>
    <title><%= yield(:page_title) || "My awesome site"%></title>
  </head>
  <body><%= yield %> </body>
</html>

app/views/posts/index.html.erb

<%= content_for :page_title, "post listing" %>
<h1>Here are your posts...</h1>
于 2009-11-27T04:55:06.903 回答
2

bodyandhead标签通常在其中一种布局中定义。布局默认位于app/views/layouts.

于 2009-11-26T20:57:34.670 回答