6

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.

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. 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.

How do I make the change permanent until a different thumbnail is clicked?

Thanks!

4

3 に答える 3

6

ページがリロードされているため、反転していると思います。

onclick の後に href= 値を有効にしたくない場合は、onclick= から false を返す必要があります。

また、念のため href="#" を設定することもできます。# どこにも行きません (ページをリロードしません)

于 2009-09-08T20:02:39.377 に答える
0

このようなことをしてみませんか (構文を完全にチェックしていないため、問題がある可能性があります。

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

タグに (name 属性ではなく) pic1 と pic2 という ID 属性を与え、画像自体に 'onclick' 属性を与えてください...

<img onclick='FirstPic()' id='pic1' src='image1.jpg' />
于 2009-09-08T20:08:07.227 に答える
0

クリックするとページが更新されていると思います。リンクを次のように変更してください。

<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>
于 2009-09-08T20:02:44.103 に答える