繁体   English   中英

如何识别使用Rails中的ruby中的ajax单击哪个图像

[英]How to indentify which image is clicked using ajax in ruby on rails

我想知道识别在网页上单击的图像的最佳方法,以便可以用该图像替换另一个div。

我的html页面看起来像这样-

<div id="image" >
    <%= link_to image_tag(@product.image1_url,:width=>180, :height=>180), selection_path, remote: true %>
</div>
<div id="image2" >
    <%= link_to image_tag(@product.image2_url,:width=>80, :height=>80), selection_path, remote: true %>
</div>
<div id="image3" >
    <%= link_to image_tag(@product.image3_url,:width=>80, :height=>80), selection_path, remote: true %>
</div>

现在,如果我单击image2,那么div中显示的id =“ image”的图像应替换为@product.image2_url 我创建了一个product.js.erb文件,如下所示-

$('#image').html("<%= escape_javascript image_tag(@product.image1_url,width: '250', height: '250') %>");

上面的js适用于一张图片。但是我无法编写正确的jquery代码来确定点击了哪张图片。 如何确定单击了哪个元素。 我认为这是相当不错的,但是我对jquery / javascript不熟悉。 还请告诉我任何有用的资源,这些资源可以帮助我学习js.erb文件中的代码。

任何指针将不胜感激。

提前致谢!!

您可以找到与this (当前js对象)最接近的div:

$('img').click(function() {
  clickedDiv = $(this).closest('div');
  clickedDiv.html( ... ); // do whatsoever you want
});

由于您将JavaScript与Rails混合使用,因此需要一种将客户端代码与服务器代码混合的方法。

一种方法是在selection_path设置一个参数,以识别单击了哪个图像,即: selection_path(image_id: '2'然后在js.erb中可以执行以下操作: $("#image<%=params[:image_id]%>").html(...)

第二种方法是使用ujs回调( https://github.com/rails/jquery-ujs/wiki/ajax )在js中设置可以在js.erb文件中使用的变量

这是我的工作示例,尽管我没有使用新的局部...我在同一页面上将所有图像都放在同一页面上,其中主图像位于顶部,小图像位于缩略图下方。 .suppose您的html文件具有主图像和图像的水平列表,其中单击任何img都会使用class选择器替换主图像的src

<!-- main image that should be replaced on click of any listing images below-->
 <div class="row">
<%= image_tag @image.image_photos.first.avatar.expiring_url(10),:class=>"img-responsive main_image_show_image",:style=>"margin: 0px auto;"%>
</div> 

<!-- this is the horizontal thumbnail image listing row which is clickable and replaces the above main image -->
 <hr>
<div class="row">
<ul class="list-inline text-center">
<% @image.image_photos.each do |i|%>
<li style="width:100px;">
<a href="javascript:void(0);" class="thumbnail change_and_add_new_show_image">
<%= image_tag i.avatar.expiring_url(10),:class=>"img-responsive ",:style=>"margin: 0px auto;"%>
</a>
</li>
<%end%>
</ul>
</div>
 <script type="text/javascript">
$(document).ready(function(){
$('.change_and_add_new_show_image').click(function(){
var img_src=$(this).find("img").attr("src");
$(".main_image_show_image").attr("src",img_src);
})//method ends
})//document ends
</script>

所以你要做的就是更换 src与主图像的one clicked

暂无
暂无

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

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