Use the setInterval() function to dynamically add css to li
<ul>
<li> 1 </li>
<li> 2 </li>
<li> 3 </li>
<li> 4 </li>
</ul>
var i = -1;
setInterval(function(){
i++;.
console.log(i);
(i > 3) ? i = -1 : changeClass(i);
}, 1000);
function changeClass(j) {
$('li').eq(j).addClass('cur').siblings().removeClass('cur');
}
It is found that the change of i is 0->1->2->3->4->0->1->2->3->4, which means After adding css to the li with subscript 3, there will be an interval of 1s before dynamic switching continues, because there is no li with subscript 4. What is causing this?
伊谢尔伦2017-05-19 10:14:53
Because (i > 3) ? i = -1 : changeClass(i); ternary operation,
When i=4 (i > 3) ? Does it mean that 4 is greater than 3? , if 4 is definitely greater than 3, execute i = -1,
The function changeClass(i) will not be executed, so there is no li with subscript 4
習慣沉默2017-05-19 10:14:53
0 - 3 is already 4. Only when you write (i > 3) will it become -1, which means it has to be run five times before it becomes -1;
If you want to run it 4 times, it will become -1 -1 should be changed to (i >= 3)
仅有的幸福2017-05-19 10:14:53
The fourth one can never be hung up, so it is recommended to change i>3 to i>4 or i>=3