在内插入 javascript 调用在导轨中

发布于 2024-08-12 08:53:05 字数 140 浏览 4 评论 0原文

我是 Rails 的新手。问题很简单,我想知道如何在 onLoad 事件的 body 标记内进行 JavaScript 函数调用。

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

谢谢

I am n00b at rails. The question is very simple, i want to know how can i make a javascript function call inside body tag on the onLoad event.

I'm asking this because in the views i can't find any body or head tag (It's like they are generated elsewhere).

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

吹泡泡o 2024-08-19 08:53:05

您无需修改​​ body 标签即可将 Javascript 函数与 onload 相关联。您可以将该函数分配给外部 Javascript 文件内的 window.onload ,而不是在主体上使用 onload 属性。

还有更高级的方法,使用事件侦听器来做同样的事情(在页面加载时触发函数),这将允许在页面加载之前的一段时间内在 DOM 上添加多个侦听器函数或触发函数。只需设置 window.onload 是最简单的方法,并且将使您的 Javascript 不引人注目。

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.

囍孤女 2024-08-19 08:53:05

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

The body and head tag would usually be defined in one of the layouts. Layouts are by default located in app/views/layouts.

故事和酒 2024-08-19 08:53:05

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

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

这是一个允许在每个页面的基础上覆盖标题的示例 中设置 script 标签。

同样的技术适用于在 HTML head标签

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

,但 /index.html.erb

<%= content_for :page_title, "post listing" %>
<h1>Here are your posts...</h1>

Eric Bréchemier and mtyaka are both correct.

Another approach (if you need to add custom elements to the header/footer that are specified on a per view basis, you'll want to do something like this with yield blocks

Here's an example allowing the title to be overriden on a per page basis, but the same technqiue applies to setting up script tags in the HTML head tag.

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>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文