在内插入 javascript 调用在导轨中
我是 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您无需修改 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.
body
和head
标记通常在其中一种布局中定义。布局默认位于app/views/layouts
中。The
body
andhead
tag would usually be defined in one of the layouts. Layouts are by default located inapp/views/layouts
.Eric Bréchemier 和 mtyaka 都是正确的。
另一种方法(如果您需要将自定义元素添加到在每个视图的基础上指定的页眉/页脚,您将需要使用收益块执行类似的操作
这是一个允许在每个页面的基础上覆盖标题的示例 中设置
script
标签。同样的技术适用于在 HTML head标签
,但 /index.html.erb
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
app/views/posts/index.html.erb