递归函数JavaScript

时间:2018-12-05 00:50:14

标签: javascript

我已经对以下递归函数进行了编码。我希望用户只要单击按钮,图片就会发生变化并不断重复。但是,一旦到达循环末尾,它将停止执行。 您能帮我解决这个问题吗?

注意:您可以在src图片中尝试 HTML:

<button  onclick="show();">show pictures</button>
<ul id="UL">
    <li id=""><img src="imagegs.jpg" class= "img1"  ></li>
    <li id=""><img src="images.jpg" class= "img1"  ></li>
    <li id=""><img src="imags.jpg" class= "img1"  > </li>
    <li id=""><img src="imas.jpg" class= "img1"  ></li>
    <li id=""><img src="coffee.jpg" class= "img1" ></li>
</ul>

css:

ul{
    list-style: none;
  }
ul li img{
    position: absolute;
    width: 250px;
    height: 250px;
}
ul li{
    display: none;
}

js:

var count=0; 

function show(){
    var pictures = document.images.length;
    var showPicture = document.getElementById('UL');
    var i = count % pictures; // to maintain the picture index not exeeding its length
    showPicture.children[i].style.display = "inline";
    count++;
    console.log("count "+count+" index: "+i); 
}

2 个答案:

答案 0 :(得分:0)

从上一张图像中删除display内联样式,然后再显示另一个:

    showPicture.children[i].style.display = "";

ul{
    list-style: none;
  }
ul li img{
    position: absolute;
    width: 250px;
    height: 250px;
}
ul li{
    display: none;
}
<script>
var count=document.images.length - 1; 
var i = 1;

function show(){
    var pictures = document.images.length;
    var showPicture = document.getElementById('UL');
 
    
    showPicture.children[i].style.display = "";    
    count++;
    
    i = count % pictures; // to maintain the picture index not exeeding its length
    showPicture.children[i].style.display = "inline";
    console.log("count "+count+" index: "+i); 
}
</script>

<button  onclick="show();">show pictures</button>
<ul id="UL">
    <li id=""><img src="https://via.placeholder.com/300x90.png?text=1" class= "img1"  ></li>
    <li id=""><img src="https://via.placeholder.com/300x90.png?text=2" class= "img1"  ></li>
    <li id=""><img src="https://via.placeholder.com/300x90.png?text=3" class= "img1"  > </li>
    <li id=""><img src="https://via.placeholder.com/300x90.png?text=4" class= "img1"  ></li>
    <li id=""><img src="https://via.placeholder.com/300x90.png?text=5" class= "img1" ></li>
</ul>

答案 1 :(得分:0)

显示图像后,您不会隐藏该图像。仅切换一个班级并记住最后一个班级就容易了。另一种选择是只读取最后一个索引。

var count = 0;
var last;
var showPicture = document.getElementById('UL');
var lis = showPicture.querySelectorAll("li")

function show() {
  var i = count % lis.length; 
  if (last) last.classList.remove("active");
  last = lis[i]
  last.classList.add("active");
  count++;
}
ul {
  list-style: none;
}

ul li img {
  position: absolute;
  width: 250px;
  height: 250px;
}

ul li {
  display: none;
}

ul li.active {
  display: block;
}
<button onclick="show();">show pictures</button>
<ul id="UL">
  <li><img src="http://placekitten.com/100/300"></li>
  <li><img src="http://placekitten.com/200/300"></li>
  <li><img src="http://placekitten.com/300/300"></li>
  <li><img src="http://placekitten.com/400/300"></li>
</ul>