javascript - 如何使用按钮遍历 <ul> ?

标签 javascript jquery html css

我正在为网站创建一种位于屏幕右侧的帮助栏。

sidebar help

我有一个由类突出显示的索引;如何循环使用这个“下一步”按钮并突出显示每个步骤?

fiddle :https://jsfiddle.net/1wvd690h/

HTML:

<button id="next-help">Next</button>

<ul id="helpBar-list" class="no-indent">
    <li class="highlight">Click on Online PO's</li>
    <li>Select the 'Total' Folder</li>
    <li>Type the name of th Supplier in the filter box</li>
    <li>Open a PO containing the items you need by clicking on the PO Number</li>
    <li>Review the PO Contents</li>
    <li>If this Purchase Order has the items you need, click on the 'Copy' icon</li>
    <li>Clicky 'Copy &amp; New' in the prompt</li>
    <li>Change quantities as necessary</li>
    <li>Review, and submit your order when ready</li>
</ul>

jQuery:

$("#next-help").click(function (){
    //should go to next index in <ul>
});

var listItems = $("#helpBar-list li");

listItems.each(function (index)
{
    //this is how i am looping through entire list, but i don't need to do that
    console.log(index + ": " + $(this).text());
});

最佳答案

怎么样

$("#next-help").on("click",function (){
  $(".highlight").removeClass("highlight").next().addClass("highlight");
});

循环保存索引进行存储

$(function() {
  var $list = $("#helpBar-list li");   
  $("#next-help").on("click",function (){
    var idx = $(".highlight").removeClass("highlight").next().index();
    if(idx==-1) idx=0; // here you can do what you want with idx
    $list.eq(idx).addClass("highlight");
  });
});

FIDDLE

$(function() {
  var $list = $("#helpBar-list li");   
  $("#next-help").on("click",function (){
    var idx = $(".highlight")
      .removeClass("highlight")
      .next()
      .index();
    if(idx==-1) idx=0;
    $list.eq(idx).addClass("highlight");
    console.log(idx);  
  });
});
.highlight {
	background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="next-help">Next</button>

<ul id="helpBar-list" class="no-indent">
    <li class="highlight">Click on Online PO's</li>
    <li>Select the 'Total' Folder</li>
    <li>Type the name of th Supplier in the filter box</li>
    <li>Open a PO containing the items you need by clicking on the PO Number</li>
    <li>Review the PO Contents</li>
    <li>If this Purchase Order has the items you need, click on the 'Copy' icon</li>
    <li>Clicky 'Copy &amp; New' in the prompt</li>
    <li>Change quantities as necessary</li>
    <li>Review, and submit your order when ready</li>
</ul>

关于javascript - 如何使用按钮遍历 <ul> ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30718917/

相关文章:

javascript - NodeJS parseStream,定义一个 block 的起点和终点

JavaScript RegExp - 查找特定字符之前的所有前缀

jquery - 如何导入 .js 文件

php - 尝试使用ajax jquery将2个变量传递给php

css - 具有 float 属性的 div 布局

html - HTML slider 的固定文本

javascript - html5可拖动隐藏原始元素

javascript - 动态字段上的自动完成 - 显示来自 mysql 对输入数据的用户建议

css - 如何使用 CSS 使子 div 增长到全屏?

javascript - DIV 宽度不合逻辑地卡住了,无法更改