如何在ruby on rails中使用ajax识别单击了哪个图像

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

本文关键字:单击 识别 ajax 图像 ruby on rails      更新时间:2023-09-26

我想知道识别我在网页上点击的图像的最佳方法,以便我可以用该图像替换另一个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中。例如:$("#image<%=params[:image_id]%>").html(...)

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

这是我的工作示例,我不使用新的部分虽然…我有所有的图像在同一页面上,其中主图像是在顶部和小图像在缩略图下面列出。 。假设你的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>

所以你所要做的就是one clicked

替换主图像的 src