简体   繁体   English

如何在jQuery中隐藏先前的li标签

[英]How to hide the previous li tag in jquery

I am working on a project in which I have a ul tag with 5 li. 我正在做一个有5 li ul标签的项目。

What I want to do is that I want to show each Items one by one on the click of a button. 我想做的是,我想通过单击按钮逐个显示每个项目。 Means as I click the button then the next item should be displayd and the previous one should be hide. 意味着当我单击按钮时,应显示下一个项目,而应隐藏上一个项目。 as generally happens in quizes. 就像通常在测验中一样。

When We click the next button, the next question appears and the previous one hides. 当我们单击下一个按钮时,出现下一个问题,而上一个隐藏。

I am using the following html code : 我正在使用以下html代码:

<div class="span12" style="margin-top:140px;">
<ul id="part">
<li id="div0" style="display:none;">Question id</li>
<li id="div1" style="display:none;">Question 2</li>
<li id="div3" style="display:none;">Question 3</li>
<li id="div4" style="display:none;">Question 4</li>
<li id="div5" style="display:none;">Question 5</li>
</ul>
<button id="next">Next</button>
</div>

and the jquery code is : 和jQuery代码是:

<script>
$(function(){
    var items = $('ul#part li');
    if(items.filter(':visible').length == 0)
    {
        items.first().show();
    }
    $('#next').click(function(e){
        e.preventDefault();
    items.filter(':visible:last').next().show();
    });
});
</script>

It is showing the next items from ul on button click but I am unable to hide the previous button. 它显示了ul单击按钮后的下一个项目,但我无法隐藏上一个按钮。

How can I hide the previous li button as I click on next. 单击下一步时,如何隐藏上一个li按钮。

Please help me 请帮我

This should work 这应该工作

<script>
$(function(){
    var items = $('ul#part li');
    if(items.filter(':visible').length == 0){
        items.first().show();
    }

    $('#next').click(function(e){
        e.preventDefault();

        var active = items.filter(':visible:last');
        active.hide();

        var next = active.next();
        if (next.length)
             next.show();
    });
});
</script>

To check if next exists you should check the length. 要检查下一个是否存在,您应该检查长度。

Working on Arek's answer, change the if condition to 处理Arek的答案,将if条件更改为

if (next.length) {
  next.show();
} else {
  $('#next').html("Submit");
}

so that the button is changed to submit. 以便将按钮更改为提交。

Demo Fiddle 演示小提琴

Var index=0;/*this should be global variable*/

('#next').click(function(e){
      e.preventDefault();
      items.hide();
      items[index].show();
      index==items.length-1?index=0:index++;
 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM