简体   繁体   English

Rails 3 - Ajax - 需要一些基本的Javascript / Jquery帮助

[英]Rails 3 - Ajax - Need help with some basic Javascript/Jquery

I'm trying to learn some javascript and have gotten stuck. 我正在尝试学习一些JavaScript并且卡住了。

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. 我想要做的就是这样做,当有人点击图片时,它会将它们超链接到我在模型数据中使用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. 我之所以也想用ajax做点什么,比如在点击图像时更新图像的得分/投票计数器。

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. 到目前为止,使用javascript我已经弄清楚如何打开一个网址,但只有我将一个硬编码到javascript中。 Here's my index.js.erb code (real simple): 这是我的index.js.erb代码(非常简单):

window.open("http://www.google.com");

But I cannot figure out how I would link to my g.source like I am in my view's do loop. 但我无法弄清楚我将如何链接到我的g.source,就像我在我的视图中的循环一样。 How do I access this model data in javascript? 如何在javascript中访问此模型数据? I have figured out how to render this code on click of the image though, with the follow in ...javascripts/application.js: 我已经想出了如何在点击图像时渲染这个代码,但是后面的... 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. 您是非常正确的道路,在一个窗口中打开图像,如果href你得到a点的图像文件。

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. "#galleries #picture a img"给你img元素,但你需要包含图像的hyperlink so we will use $(this).closest("a") to get hyperlink for image url. 所以我们将使用$(this).closest("a")来获取图片网址的hyperlink链接。

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

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