简体   繁体   English

如何指定用于运行javascript'document.ready'的视图或控制器

[英]how to specify the view or controller for running javascript 'document.ready'

I want to run javascript like bellow when the page is loaded. 加载页面时,我想运行波纹管这样的javascript。

$ ->
  $.getJSON '/memos.json', (data) ->
    $.each( data ), (key,memo)->
      $('#memos').append( "#{memo.title} #{memo.content}<br/>") 

but I want to run this only after 'users/show.html.erb' is loaded. 但我只想在加载“ users / show.html.erb”之后运行它。 the view is like bellow 风景就像波纹管

<div id="memos"></div>

I think there are two approaches to do this. 我认为有两种方法可以做到这一点。 One is to specify the views loaded, and the second one is to specify the controller. 一种是指定加载的视图,第二种是指定控制器。

I don't think writing javascript on erb file is a good idea. 我认为在erb文件上编写javascript不是一个好主意。 Is there any way to implement them? 有什么办法可以实现它们?

thanks. 谢谢。

the

$ ->
    ..

on the first line, will be translated to 在第一行,将被翻译为

$(function() {
  ...
});

which is basically is a shorthand for JQuery's 这基本上是JQuery的简写

$(document).ready(function() {
  ...
});

which means that the script inside of this function will only be executed once the DOM is ready. 这意味着该函数内部的脚本仅在DOM准备就绪后才会执行。

so You could save the javascript into separate file let say js/memos/index.js and within your view app/views/memo/index.html.erb' you would have the ` and on the same file you can include the javascript with javascript include tag. 因此,您可以将javascript保存到单独的文件中,例如js/memos/index.js并在view app/views/memo/index.html.erb' you would have the `,并且可以在同一文件中包含javascript javascript include标签。

The javascript will only be executed once DOM is ready, meaning at that point you will already have the div. 仅在DOM准备就绪后才执行JavaScript,这意味着此时您已经有了div。

More info on JQuery's ready http://api.jquery.com/ready/ 在JQuery的更多信息ready http://api.jquery.com/ready/

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

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