如何展开一个 div,然后单击将一个 div 添加到列表中的下一项

我之前问过一个问题(删除一个类,然后在单击按钮时将一个类添加到纲要中的下一个项目),虽然这个问题有效,但我问了错误类型的问题。在删除和添加一个类的过程中,我试图在另一个 div 中包装和展开一个 div,并在单击时将一个 div 包装在下一个项目中。


我想要做的是删除.current围绕项目 1的 div 包装并包装.current在纲要中的下一个项目(项目 2)上调用的 div 。


我的代码:


(function() {

  $("#next-item").on("click", function() {

    var curr = $('.nav-right').children('.current'); //find .current

    if (curr.next().length > 0) { // If you want to stop at last element

      curr.next().wrapInner('current'); //wrap a div around next item

      curr.contents().unwrap(); //unwrap div from previous item

    }

  });

});

.current {

  border: 1px solid

}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<!--button to advance-->

<button id="next-item">next item</button>

<!--list of items to rundown-->

<div class="nav-right">

  <!--first item-->

  <div class="irl-today-item">

    <div class="current">item 1</div>

  </div>

  <div class="irl-today-item">item 2</div>

  <div class="irl-today-item">item 3</div>

  <div class="irl-today-item">item 4</div>

  <div class="irl-today-item">item 5</div>

</div>

JS小提琴:https : //jsfiddle.net/openbayou/wzt6bp0d/


隔江千里
浏览 174回答 2
2回答

陪伴而非守候

下面的代码使 onclick 具有循环的能力,即使从开始到结束也是如此:$(function(){&nbsp; &nbsp; // store all items&nbsp;&nbsp; &nbsp; var allItems =&nbsp; $(".nav-right").children();&nbsp; &nbsp; // initialize for loop counter&nbsp; &nbsp; var i = 0;&nbsp; &nbsp; // onclick&nbsp; &nbsp; $("#next-item").on("click", function(){&nbsp; &nbsp; &nbsp; &nbsp;// select the current item&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;var wrapper = document.querySelector('.current');&nbsp; &nbsp; &nbsp; &nbsp;// removing the current wrapper&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;wrapper.outerHTML = wrapper.innerHTML;&nbsp; &nbsp; &nbsp; &nbsp;// looping and wrap the next item with current div&nbsp; &nbsp; &nbsp; &nbsp;i = (i + 1) % allItems.length;&nbsp; &nbsp; &nbsp; &nbsp;allItems.eq(i).wrapInner('<div class="current"></div>');&nbsp; &nbsp; });});根据@daniel-beck 的建议更新:$(function(){&nbsp; &nbsp; // store all items&nbsp;&nbsp; &nbsp; var allItems =&nbsp; $(".nav-right").children();&nbsp; &nbsp; // initialize for loop counter&nbsp; &nbsp; var i = 0;&nbsp; &nbsp; // onclick&nbsp; &nbsp; $("#next-item").on("click", function(){&nbsp; &nbsp; &nbsp; &nbsp;// select the current item and remove the current wrapper&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;$('.current').contents().unwrap();&nbsp; &nbsp; &nbsp; &nbsp;// looping and wrap the next item with current div&nbsp; &nbsp; &nbsp; &nbsp;i = (i + 1) % allItems.length;&nbsp; &nbsp; &nbsp; &nbsp;allItems.eq(i).wrapInner('<div class="current"></div>');&nbsp; &nbsp; });});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript