【问题标题】:Change image without page refresh or reload在不刷新页面或重新加载的情况下更改图像
【发布时间】:2015-01-02 16:15:22
【问题描述】:

我正在使用本指南。

http://jsfiddle.net/nz8qy41y/

问题: 当我点击 [1] [2] 或 [3] 时,主图像没有改变。相反,我被重定向到图像。

查看。 主图:

<div class="block-2-image"> 

<a href=<%=@advertisement.pictures.first.image.url(:original)%> data-lightbox="gallery"><%=  image_tag @advertisement.pictures.first.image.url(:medium),
    :title=> @advertisement.name,:id=>"main-image", :alt =>                                   @advertisement.name%></a>

</div>

缩略图:

<ul class="thumbnail">
    <% @advertisement.pictures.to_enum.with_index(1) do |thumb, index|%>


         <li><a href=<%=thumb.image.url(:medium)%>><%= index %></a></li>


    <% end %> 
</ul>

脚本:

$(document).ready(function(){
   $('.thumbnail li').on('click',function(){
      $('.block-2-image a').find('img').attr('src', $(this).attr('src'));
   });
});

现在,当我单击小图像时,它会链接到正确的图像,但在其他视图中。 我需要在同一视图中更改图像。

有什么帮助吗?

谢谢。

【问题讨论】:

  • Maybe just change image path when click to those number images happen?你试试
  • 类似fiddle
  • @BogdanKuštan Tnx。但是我的代码不会改变主图像,它只是重定向到正确的图像路径。脚本有什么问题?
  • @EdgarsRozenfelds 在click 回调函数中您应该传递event 参数(在我的示例中为变量e)和内部函数调用event.preventDefault()

标签: javascript jquery html ruby-on-rails image


【解决方案1】:

如果不包含 jquery,则包含它 在 jquery 中

$(document).ready(function(){
   $('.thumbnail li img').on('click',function(){
      $('.block-2-image').find('img').attr('src', $(this).attr('src'));
   });
});

但这样最好在 html 中为您的图像键入完整路径

【讨论】:

    【解决方案2】:

    @Mohamed 答案的纯 JS 变体(未测试):

    window.onload = function() {
        var selector = document.querySelector(".thumbnail li img");
        selector.addEventListener("click", function() {
            var img = document.querySelector(".block-2-image img");
            img.setAttribute("src", selector.getAttribute("src"));
        });
    }
    

    【讨论】:

    • 谢谢。但想法是避免在该选择中使用小缩略图。我有代表图像编号而不是缩略图的不同图像。
    • 很抱歉,您能改写一下吗?我仍然想念我想念的东西。
    • @eatonphill 您的代码将主图像更改为缩略图,但我不需要。我需要能够单击四个小图像之一,然后从其他路径更改主图像。
    • “从其他路径更改主图像”是什么意思?
    • 我真的不确定。尽管看起来您现在的问题是什么,但它超出了原始问题的范围。如果我开始正确理解您,我们的任何一个答案都应该可以满足您的需求。如果您需要先对 src 字符串进行操作,那么就这样做。但我无法准确理解您的需求。
    【解决方案3】:

    这是我的错。

    我在 Application.js 中有重复的脚本代码,混淆了所有内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-12
      • 1970-01-01
      • 2020-10-04
      相关资源
      最近更新 更多