将数组元素替换为id标记

replace array element as id tag

本文关键字:id 标记 替换 数组元素      更新时间:2023-09-26

数组中的元素是下面代码的假定id标记,但它在这里似乎不起作用。每次调用highlight函数时,它都应该从上一个id标记中删除当前类,并且当前类应该指向充当id标记的下一个数组元素。

HTML代码

<p class="current" id="one">Point 1</p>
<p id="two">Point 2</p>
<p id="three">Point 3</p>
<p id="four">Point 4</p>
<p id="five">Point 5</p>
<p id="six">Point 6</p>
<p id="seven">Point 7</p>

Java脚本代码

//The array element is suppose to be the next id tag  and it should keep replacing as the function is called.
function highlight() {
    var point = ["one", "two", "three", "four", "five", "six", "seven"];
    var i = 0;
    $("#point[i]").removeClass("current"); //#point[i] doesn't seems to replace this thing
    i++
    if (i > 6) {
        i = 0;
    }
    $("#point[i]").addClass("current");
}
setTimeout(highlight, 5000);

你能不简单地这么做吗?

(function highlight() {
    setTimeout(function() {
        var $current = $("p.current").removeClass("current");
        var $next = $current.next().length && $current.next() || $current.siblings().first();
        $next.addClass("current");
        highlight();
    }, 1000);
}());

(function highlight() {
    setTimeout(function() {
        var $current = $("p.current").removeClass("current");
        var $next = $current.next().length && $current.next() || $current.siblings().first();
        $next.addClass("current");
        highlight();
    }, 1000);
}())
.current {
    color: green;
    font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <p class="current" id="one">Point 1</p>
  <p id="two">Point 2</p>
  <p id="three">Point 3</p>
  <p id="four">Point 4</p>
  <p id="five">Point 5</p>
  <p id="six">Point 6</p>
  <p id="seven">Point 7</p>
</div>

正如@lshettyl的建议,我也改为setInterval((来回放每个时间间隔:

var i = 0;
function highlight() {
  var point = ["one", "two", "three", "four", "five", "six", "seven"];
  $("#" + point[i]).removeClass("current"); //#point[i] doesn't seems to replace this thing
  i++
  if (i > 6) {
    i = 0;
  }
  $("#" + point[i]).addClass("current");
}
setInterval(highlight, 1000);

希望得到帮助。

您需要重新运行highlight并设置对前一个元素的引用。

var $prior = null;
var point = ["one", "two", "three", "four", "five", "six", "seven"];
var i = 0;
function highlight() {
  if ($prior != null) $prior.removeClass("current");
  var id = '#' + point[i];
  
  i++;
  if (i > 6) {
    i = 0;
  }
  $(id).addClass("current");
  $prior = $(id);
  setTimeout(highlight, 500);
}
highlight();
.current {
  background-color:#aacc66;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="current" id="one">Point 1</p>
<p id="two">Point 2</p>
<p id="three">Point 3</p>
<p id="four">Point 4</p>
<p id="five">Point 5</p>
<p id="six">Point 6</p>
<p id="seven">Point 7</p>