简体   繁体   English

如何使用JavaScript变量获取Rails网址

[英]How to use javascript variable to get a rails url

I have an image link that looks like this: 我有一个看起来像这样的图像链接:

<a href="#user-image-modal" data-toggle="modal" data-id="<%= image.id %>"><img class="user-photo" src="<%= image.picture.medium.url %>" alt="" /></a>

and a modal that looks like this: 模态如下:

  <div id="user-image-modal" class="modal" tabindex="-1" role="dialog" aria-labelledby="user-image" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        </div>
        <div class="modal-body">
          <img src="" alt="">
        </div>
        <div class="modal-footer">
        </div>
      </div>
    </div>
  </div>

When the image link is clicked I want to open a larger version of the image. 单击图像链接后,我想打开较大版本的图像。 The url of the image is obtained from a carrierwave helper UserImage.find(id).picture.large.url . 图像的URL是从UserImage.find(id).picture.large.url助手UserImage.find(id).picture.large.url

My js.erb file: 我的js.erb文件:

  $('#user-image-modal').on('show.bs.modal', function (event) {
    var link = $(event.relatedTarget)
    var photo = link.data('id')
    var modal = $(this)

    // What comes next?
  })

I need to set the src attribute in the img tag of the modal with UserImage.find(photo).picture.large.url . 我需要使用UserImage.find(photo).picture.large.url在模态的img标记中设置src属性。 The photo variable corresponds to the id of the UserImage record. 照片变量对应于UserImage记录的ID。 How can I use the photo variable to get the correct url. 如何使用photo变量获取正确的网址。 I don't think I can use the photo variable inside erb tags. 我认为我不能在erb标签中使用photo变量。

Add the large picture url to the link as a data attribute, like it is done with the id attribute. 将大图片网址作为数据属性添加到链接中,就像使用id属性一样。 Then (on click) get the url and do whatever you want. 然后(单击)获取URL并执行您想要的任何操作。

<a href="#user-image-modal" data-toggle="modal" data-url="<%= image.picture.large.url %>">
  <img class="user-photo" src="<%= image.picture.medium.url %>" alt="" />
</a>

$('#user-image-modal').on('show.bs.modal', function (event) {
  var link = $(event.relatedTarget);
  var imgSrc = link.data('url');
  var modal = $(this);

  modal.find(".modal-body img").attr('src', imgSrc);
})

Another way is to send an AJAX query with the given id to get the picture. 另一种方法是发送具有给定id的AJAX查询以获取图片。

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

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