【问题标题】:How to print index of nth-child(n) per seconds?如何每秒打印 nth-child(n) 的索引?
【发布时间】:2018-09-19 06:05:21
【问题描述】:

这是我的代码,但在打印 nth-child(n) 的索引后它一直打印 -1。

有什么方法可以每秒打印 nth-child(n) 的索引吗? (对不起我的英语不好)

x=0
$(setInterval(function(){
  x++;
  i = x%3;
  n = $('.modelbox a:nth-child('+ i +')').index();
  if(i == 0){
    document.write(n)
  } else if(i == 1){
    document.write(n)
  } else if(i == 2){
    document.write(n)
  } else if(i == 3){
    document.write(n)
  }
}, 1000))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="modelbox">
    <a href="#"><img src="imgmodel/header01.jpg" width="100%"></a>
    <a href="#"><img src="imgmodel/header02.jpg" width="100%"></a>
    <a href="#"><img src="imgmodel/header03.jpg" width="100%"></a>
    <a href="#"><img src="imgmodel/header04.jpg" width="100%"></a>
  </div>

【问题讨论】:

  • document.write...

标签: javascript if-statement indexing css-selectors setinterval


【解决方案1】:

永远不要使用document.write。它将调用document.open(),这样做会删除您文档中的所有内容(因此您有以下-1)。

现在,您的代码中存在另一个问题,即您使用的是从零开始的索引,而 nth-child() 是从 1 开始的。所以你需要将1添加到i:

x = 0
$(setInterval(function() {
  x++;
  i = x % 3;
  n = $('.modelbox a:nth-child(' + (i + 1) + ')').index();
  if (i == 0) {
    console.log(n)
  } else if (i == 1) {
    console.log(n)
  } else if (i == 2) {
    console.log(n)
  } else if (i == 3) {
    console.log(n)
  }
}, 1000))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="modelbox">
  <a href="#"><img src="imgmodel/header01.jpg" width="100%"></a>
  <a href="#"><img src="imgmodel/header02.jpg" width="100%"></a>
  <a href="#"><img src="imgmodel/header03.jpg" width="100%"></a>
  <a href="#"><img src="imgmodel/header04.jpg" width="100%"></a>
</div>

【讨论】:

  • 感谢您解决我的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-04-14
  • 1970-01-01
  • 2017-06-09
  • 2021-09-15
  • 1970-01-01
  • 1970-01-01
  • 2012-06-26
相关资源
最近更新 更多