Changing img src javascript

Changing img src javascript

本文关键字:javascript src img Changing      更新时间:2023-09-26

我试图用javascript在我的页面上交换图像,我有几个产品,每个产品的拇指,当拇指被点击时,主图像被改变。但是…当我加入一个以上的生成物时,两个都改变了。他们有独立的id,但两者都在改变。下面是标题

中的脚本
  function changeImage(imgName)
  {
     image = document.getElementById('numberone');
     image.src = imgName;
     image = document.getElementById('othertwo');
     image.src = imgName;
 }
Html

<img src="images/products/vests/classy_clay_beige_vest_front.JPG" alt="beige" width="350" height="400" id="numberone">

和拇指

<div class="thumb1">
     <img src="images/products/vests/classy_clay_beige_vest_front_thumb.JPG" alt="beige" width="80" height="91" onclick="changeImage('images/products/vests/classy_clay_beige_vest_front.JPG')">
</div>
<div class="thumb2">
    <img src="images/products/vests/classy_clay_beige_vest_back_thumb.JPG" alt="navy" width="80" height="91" onclick="changeImage('images/products/vests/classy_clay_beige_vest_back.JPG')">
</div>

链接到网站

您的问题是更新图像函数更新所有产品预览,您需要传递您想要更新的产品预览的id,如下所示:

onclick="changeImage("numberone",'images/products/vests/classy_clay_beige_vest_front.JPG')"

并将更新函数替换为下面的

changeImage(id,url){
    image = document.getElementById(id);
    image.src = url;
}

为了更容易地添加更多产品,您可以使用一致的类,并使用它们在页面上显示的顺序。第一个是document.getElementsByClassName("thumb-large")[0],以此类推。然后,不是传递id,而是传递引用。

稍微调整一下结构,并使用jQuery(您标记了问题),这将为您工作:

<img src="images/products/vests/classy_clay_beige_vest_front.JPG" alt="beige" width="350" height="400" id="numberone">
<div class="thumbs">
    <div class="thumb1">
        <img src="images/products/vests/classy_clay_beige_vest_front_thumb.JPG" alt="beige" width="80" height="91" data-large-src="images/products/vests/classy_clay_beige_vest_front.JPG">
    </div>
    <div class="thumb2">
        <img src="images/products/vests/classy_clay_beige_vest_back_thumb.JPG" alt="navy" width="80" height="91" data-large-src="changeImage('images/products/vests/classy_clay_beige_vest_back.JPG">
    </div>
</div>
jQuery(function($) {
    $('div.thumbs img').click(
        function() {
               $('#numberone').attr('src', ($(this).attr('data-large-src'));
        }
    });
});

您想要这样的交换吗?

请查看这个DEMO。

$(".thumb").click(function(){
 var tmp=$(this).find("img").attr("src");
 $("#numberone").attr("src",tmp);
})

像下面这样写代码会更简洁。

 function changeImage(imgName)
  {
     document.getElementById('numberone').src = imgName;
     document.getElementById('othertwo').src = imgName;
 };

你必须写的脚本越少越好,这样当对嵌入JavaScript的.js文件或html文件的请求被分割到客户端时,有效负载就越轻。