javascript没有按预期工作按钮

时间:2013-10-14 14:24:14

标签: javascript html

我正在尝试将之前和之前的按钮连接到图库,我希望之前的按钮隐藏在图库的第一个图像上,但javascript似乎根本不起作用。

的Javascript

var imageGallery = new Array();
imageGallery[0] = '1.png';
imageGallery[1] = '2.png';
imageGallery[2] = '3.png';
imageGallery[3] = '4.png';
imageGallery[4] = '5.png';
var imgCount = 0;
function next() {
    imgCount++ ;
    document.getElementById("gallery").src = imageGallery[imgCount] ;
}

function previous() {
    imgCount--;
    document.getElementById("gallery").src = imageGallery[imgCount] ;   
    }
if(document.getElementById("gallery").getAttribute("src") == "1.png")
    {
    document.getElementById("previous").style.visibility = 'hidden';
    }
else 
    {
    document.getElementById("previous").style.visibility = 'visible';
    }

HTML

<div id="img">
<img id="gallery" src="1.png" style="height:420px; width:744px" >
<div id="imgNav">
    <a id="previous" href onclick="previous(); return false;">previous</a>
    <span style="color:#666; font-size:0.9em"> | </Span>
 <a id="next" href onclick="next(); return false;">next</a>
</div>
</div>

实际上,逻辑是如果id'gallery'的'src'属性是'1.png',那么id为'previous'的元素的'visibility'就是'隐藏',否则它似乎不起作用。任何人都可以帮忙搞清楚。

1 个答案:

答案 0 :(得分:1)

您可能正在尝试检查尚未完全加载的图像。您是否记得在页面完全加载时将代码置于运行状态(如果它放在页眉中 - 您没有提及它是否存在)?

<强>已更新

var imageGallery = new Array();
imageGallery[0] = '1.png';
imageGallery[1] = '2.png';
imageGallery[2] = '3.png';
imageGallery[3] = '4.png';
imageGallery[4] = '5.png';

var imgCount = 0;

function checkNav() {
    var previousLnk = document.getElementById("previous");
    var nextLnk = document.getElementById("next");

    previousLnk.style.visibility = imgCount == 0 ? 'hidden' : 'visible';
    nextLnk.style.visibility = imgCount >= (imageGallery.length - 1) ? 'hidden' : 'visible';
}

function setImg() {
    var gallery = document.getElementById("gallery");

    gallery.src = imageGallery[imgCount];
}

function next() {
    imgCount++;
    setImg();
    checkNav();
}

function previous() {
    imgCount--;
    setImg();
    checkNav();
}

window.onload = function () {
    checkNav();
}

演示:http://jsfiddle.net/N7V9E/