如何在ruby on rails中使用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中。例如:$("#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
- 使用clickToggle并在单击另一个元素时关闭元素
- 单击时将焦点更改为元素
- 单击F5时如何停止页面加载
- 通过单击表单中的按钮,在代码生成中使用javascript生成字母数字代码
- 在单击任何位置时隐藏元素,而不检查每次DOM单击
- 通过单击事件识别画布上的对象
- 识别切换条元素文本并在量角器中单击它
- 更改类,但单击不识别新类
- 无法识别JQuery单击事件
- jQuery已停止识别单击事件
- 识别在闪光灯元件上的鼠标单击
- 我们如何识别“上一个活动类是左或右”,当显示子菜单调用单击链接时
- 无法识别 Mozilla Firefox 中的右键单击事件
- jQuery完成的多部分表单需要两次单击才能识别.submit()和.click()事件处理程序
- 如何识别在每个()函数中单击的元素是相同的
- 如何在ruby on rails中使用ajax识别单击了哪个图像
- 在Jquery上下文菜单中,我如何识别右键单击的元素是否正确?
- 识别在表中单击了哪个按钮
- 在jQuery中识别单击的目标的子元素
- 无法识别输入单击