简体   繁体   English

使用Javascript更改IMG SRC

[英]Changing IMG SRC with Javascript

I'm new at javascript and while there are many more complex solutions, I don't understand them and hope I don't have to at this point. 我是javascript的新手,虽然有许多更复杂的解决方案,我不理解它们,希望我不必在这一点上。

I have a main picture... 我有一张主图......

<img src="main-picture.jpg" name="Mainpic" id="image">

...and I want to be able to change this picture when I click on one of two thumbnails. ...当我点击两个缩略图中的一个时,我希望能够更改此图片。

<a href="" onclick="FirstPic()"><img src="replacement1.jpg" name="pic1"></a>
<a href="" onclick="SecPic()"><img src="replacement2.jpg" name="pic2"></a>

My javascript code I thought would be super easy. 我认为我的javascript代码非常简单。 I'm currently using... 我目前正在使用......

function FirstPic(){
        document.Mainpic.src = document.pic1.src
        return
    }

function SecPic(){
        document.Mainpic.src = document.pic2.src
        return
    }

Now the variable is changing however it's not staying changed. 现在变量正在改变,但它不会保持变化。 When the thumbnail is clicked on, the replacement picture flashes on the screen and then it returns to the original main-picture.jpg. 单击缩略图时,替换图片在屏幕上闪烁,然后返回到原始的main-picture.jpg。

How do I make the change permanent until a different thumbnail is clicked? 在单击其他缩略图之前,如何使更改成为永久更改?

Thanks! 谢谢!

I think it's flipping back because your page is reloading. 我认为它正在翻转,因为你的页面正在重新加载。

You need to return false from your onclick= if you don't want the href= value to activate after your onclick. 如果您不希望在onclick之后激活href =值,则需要从onclick =返回false。

Also, you can set href="#" just in case. 此外,您可以设置href =“#”以防万一。 # goes nowhere (doesn't ever reload the page) #无处可去(不会重新加载页面)

I think your page is refreshing by your click, change your links as : 我认为您的页面通过点击更新,将链接更改为:

<a href="" onclick="FirstPic(); return false;"><img src="replacement1.jpg" name="pic1"></a>
<a href="" onclick="SecPic(); return false;"><img src="replacement2.jpg" name="pic2"></a>

Why not do something like this (haven't checked the syntax completly, so it could be faulty. 为什么不做这样的事情(没有完整地检查语法,所以它可能是错误的。

function FirstPic()
{
    var pic1 = document.getElementById("pic1"); 
    if (pic1 == typeof('undefined')) return;
    pic1.src = "newpicname.jpg";
}

Make sure you give the tags an ID attribute called pic1 and pic2 (instead of a name attribute) and give the image itself an 'onclick' attribute... 确保为标签提供名为pic1和pic2的ID属性(而不是名称属性),并为图像本身提供“onclick”属性...

<img onclick='FirstPic()' id='pic1' src='image1.jpg' />

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

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