Run JavaScript function onLoad in a Rails view?
my rails view looks like this (it is a partial):
=javascript_include_tag :defaults
#scroller
-@other_images.each do |img|
.thumbnail_wrapper
.t开发者_JS百科humbnail_image
=image_tag img.image.url(:thumbnail), :class => 'button', :onClick => "replaceImg(#{img.id});", :onLoad => "setLastID(#{ @other_images[0].id });"
I want to call the function setLastID(#{ @other_images[0].id }); only once, when the whole view loads. However, I couldn't figure out how... this was the only place I could put it where it worked. But now it's been called each time within the loop... Help!!
This is an example where you want to dynamically generate the javascript in the partial, since ruby variables are required. As long as these sorts of calls are very short, I'm fine with it.
=javascript_include_tag :defaults
#scroller
-@other_images.each do |img|
.thumbnail_wrapper
.thumbnail_image
=image_tag img.image.url(:thumbnail), :class => 'button', :onClick => "replaceImg(#{img.id});"
:javascript
setLastID(#{@other_images[0].id});
Have you considered loading a js.erb template instead? You can add to the dom using javascript instead of haml, and you still have access to your Rails variables. If you don't need to use that javascript function setLastID() anywhere else, you can define it right there in your js.erb template instead of some javascript file. If you do need it elsewhere, then make sure that your javascript file is loaded correctly. Reference the file in your layout, and then in the javascript file, just do something like this:
$(document).ready(function() {
alert("I'm loaded!");
});
Do it unobtrusively. tag your last image with a class (we'll use "button-last" for the sake of argument) and put it in the document.ready() event in a javascript behind the scenes, like application.js (this works if you're using jquery, you'd need to translate it to your framework of choice):
$(document).ready(function(){
setLastID($("img.button-last").attr("id"));
});
精彩评论