如何点击按钮显示下一篇文章

How to show next article on click of a button

本文关键字:一篇 文章 何点击 按钮 显示      更新时间:2023-09-26

我需要在单击按钮时隐藏和显示不同的文章。这就像一步一步的指令。这里我有下面的代码块

<article class="content-1">Content 1
    <button type="button" class="continue">Continue</button>
</article>
<article class="content-2">Content 2
    <button type="button" class="continue">Continue</button>
</article>
<article class="content-3">Content 3
    <button type="button" class="continue">Continue</button>
</article>

查询

$('.continue').click(function()
    $(this).parents('div').next('article').show();
});

现在点击.continuebutton,我需要隐藏当前文章并显示下一篇文章。有人能提前帮我解决这个问题吗?谢谢。

注意:达到最后一个article应停止该功能。

DEMO

您的js中有一些错误。您可以尝试以下操作:

$('.continue').click(function () {
    if ($(this).parent("article").next().length > 0) { //check if there is more articles
        $(this).parent("article").next().show(); //show next article
        $(this).parent("article").hide(); //hide present article
    }
});

小提琴

您可以使用以下解决方案:

我已经更改了一些css和html标记类

更改了类名,添加了通用类名

<article class="content">Content 1
    <button type="button" class="continue">Continue</button>
</article>

使用closest()查找最近的父对象。

$(".continue").on("click",function(){
    if($(this).closest(".content").next(".content").length > 0){
       $(this).closest(".content").hide();
       $(this).closest(".content").next(".content").show();
    }
});

CSS

.content:not(:first-of-type) {
    display:none;
}

演示

试试这个:先隐藏所有文章,然后找到下一篇文章来显示它,如果下一篇不存在,那么停止函数。

$(function(){
    $('.continue').click(function(){
      var next = $(this).closest('article').next();
      //check if next article is present or not
        if(next.length!=0)
        {
            $('.continue').closest('article').hide();
            next.show();
        }
     });
});

演示

您可以使用closest()来获取父项目。然后您可以将.next().hide() 一起使用

脚本

$('.continue').on('click', function(){
    var article = $(this).closest('article');    
    if(article.next('article').length){
        article.next('article').show();
    }else{
        $('article').first().show(); //If you want to use continuous loop use it else just delete this line
    }    
    article.hide()
})

DEMO

http://jsfiddle.net/kaqr6ysn/4/

你可以简单地这样做:

$('button.continue').click(function(){
  $(this).parent().hide().next().show();
});

不过,你还没有解释最后该做什么。假设您将从最后一个article中省略继续按钮?


更新:如果你想知道为什么你的小提琴不起作用:

  • 你没有选择jQuery
  • 您在第1行中省略了{
  • 您在第2行引用了div而不是article
  • 你忽略了.hide()这篇文章

试试这个:-

$('button').click(function(){
var ar = $(this).parent('article');
if (ar.next().length)
{
    ar.hide().next().show();
 }
});

演示