网页中的图像会短暂显示然后消失

时间:2014-10-25 12:02:47

标签: javascript jquery html

我在当前目录中有很多图像文件,例如step_graph0.png,step_graph1.png, step_graph2.png , step_graph3.png等等。

我的目标是能够使用单个网页逐一显示它们。我创建了两个链接,next和previous,并向它们添加了onclick方法,以便更改image.src属性。代码如下

<html>
    <head>
    <script type="text/javascript">

    window.onload =function f()  {

    f.me  = f.me || 0;

    //alert(f.me);

    var p =document.getElementById("previous");
    var n =document.getElementById("next");
    var image = document.getElementById("graph");

    alert(f.me);

    p.onclick = function(){
        f.me = f.me|| 0;
        if( f.me >  0 ) f.me--;
        image.src = "step_graph"+(parseInt(f.me) ) + ".png";


        //window.location.reload();
    }

    n.onclick = function(){
        f.me = ++f.me || 0;
        image.src = "step_graph"+(parseInt(f.me) )+".png";


        //window.location.reload();
    }


    }       

    </script>
    </head>
    <body>
        <a id="previous" href="">step_back</a> <a id="next" href="">step_forward</a><br>
        <center>
        <img id="graph" src ="step_graph1.png" ></img></center>
        code<br>
        output<br>

    </body>
</html>

我将此文件作为index.html保存在与图像相同的目录中。最初,它显示图像。但是,当我单击下一个和上一个链接时,它会显示所需的图像,但在几毫秒内,它只会返回到原始图像。我使用f.me作为静态变量来保存图像文件索引,例如文件名0, 1 , 2 , 3中的step_graph0.png, step_graph1.png, step_graph2.png等。

我试了一个小时。我认为这是关于window.onload功能重置一切。但这只是一个让我满意的猜测。

我有人可以在代码中找出错误,请这样做。

1 个答案:

答案 0 :(得分:1)

&#13;
&#13;
    var me = me || 0;

     //alert(f.me);

    var p = document.getElementById("previous");
    var n = document.getElementById("next");
    var image = document.getElementById("graph");



    $('#previous').on('click', function(e) {
      $('#try').html('prev');
      e.preventDefault();
      me = me || 0;
      if (me > 0) me--;
      image.src = "http://home.iitk.ac.in/~amitkum/images/" + (parseInt(me)) + ".jpg";
      //window.location.reload();
    });

    n.onclick = function(e) {
      e.preventDefault();

      me = ++me || 0;
      image.src = "http://home.iitk.ac.in/~amitkum/images/" + (parseInt(me)) + ".jpg";


      //window.location.reload();
    }
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body> <a id="previous" href="#">step_back</a>  <a id="next" href="#">step_forward</a>

  <br>
  <br>
  <img id="graph" src="http://home.iitk.ac.in/~amitkum/images/2.jpg" height="100"></img>
  <div id="try">jk</div>
&#13;
&#13;
&#13;

相关问题