I'm trying to learn some javascript and have gotten stuck.
Right now, I have a really stupid simple gallery/image application. What I'm trying to do is make it so, when someone clicks an image, it hyperlinks them to a url I have in my model data all with ajax. The reason why is I'd like to also do something with ajax, like update a score/vote counter for the image when it is clicked.
Right now in the view I do this with:
<% @galleries.each do |g| %>
<% for image in g.images %>
<div id="picture">
<%= render 'top_nav'%>
<%= link_to image_tag(image.file_url(:preview)), g.source, :remote => true, :target => "_blank" %>
So far, with javascript I've figured out how to open a url, but only if I hardcode one into the javascript. Here's my index.js.erb code (real simple):
window.open("http://www.go开发者_运维百科ogle.com");
But I cannot figure out how I would link to my g.source like I am in my view's do loop. How do I access this model data in javascript? I have figured out how to render this code on click of the image though, with the follow in ...javascripts/application.js:
$(function() {
$("#galleries #picture a img").live("click", function() {
$.getScript(this.href);
return false;
});
});
Anyone have any pointers on how I can start interacting with my application's data rather than hardcoding a url in the open?
Thanks
You are pretty much on the right path to open image in a window, if the href
you get from a
points to image file.
Try with this code:
$(function() {
$("#galleries #picture a img").live("click", function() {
var lnk = $(this).closest("a").attr("href");
window.open(lnk);
return false;
});
});
"#galleries #picture a img"
is giving you img
elements but you need the hyperlink
which contains the image. so we will use $(this).closest("a")
to get hyperlink
for image url.
精彩评论