使用 jQuery 切换博客文章(展开/折叠)

发布于 2024-09-27 22:06:15 字数 441 浏览 0 评论 0原文

在我的博客中,有些文章很长。所以我希望长文章在页面加载时折叠起来。它只适用于我的一篇文章,但如果我有更多文章,某些东西似乎会被破坏。

我是这样做的:

$('div#ttoggle').hide();
$('#btoggle').click( function() {
    if($('div#btoggle p').text() == 'expand article'){
        $('div#btoggle p').text('collapse article');
    }else{
        $('div#btoggle p').text('expand article');              
    }   

    $('div#ttoggle').slideToggle("slow");           
});

有什么想法吗?

in my blog some articles are very long. So I want the long articles to be collapsed when the page is loaded. It works for me for just one article but if I have more articles something seems to be broken.

Here's how I do it:

$('div#ttoggle').hide();
$('#btoggle').click( function() {
    if($('div#btoggle p').text() == 'expand article'){
        $('div#btoggle p').text('collapse article');
    }else{
        $('div#btoggle p').text('expand article');              
    }   

    $('div#ttoggle').slideToggle("slow");           
});

Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

踏月而来 2024-10-04 22:06:15

您似乎正在使用 id 选择器来表示您声明将在页面上多次出现的内容。 id 属性必须是唯一的,因此这将是无效的 HTML,并可能导致失败。

这里的解决方案是将所有id替换为class。您可以使用.classname选择器来选择适当的元素

You seem to be using an id selector for something which you state will appear multiple times on the page. id attributes must be unique, so this would be invalid HTML and could be causing this to fail.

The solution here would be to replace all ids with classes. You can use the .classname selector to select the appropriate elements

岁月苍老的讽刺 2024-10-04 22:06:15

您正在使用 ids“#btoggle”,您可能需要类。您应该只拥有一个具有给定 id 的元素。

您将点击处理程序分配给多个元素,然后通过重新检查所有元素来决定要做什么。相反,在处理程序中使用 this 来仅考虑单击的元素:(

$('div#ttoggle').hide();
$('#btoggle').click( function() {
    var tog = $(this);
    var togp = tog.find("p");    
    if (togp.text() == 'expand article') {
        togp.text('collapse article');
    }
    else {
        togp.text('expand article');              
    }   

    tog.siblings('div#ttoggle').slideToggle("slow");
});

我不知道您的 HTML 实际上是什么样子,我对兄弟姐妹进行了猜测。)

You are using ids "#btoggle" where you probably want classes. You should only ever have a single element with a given id.

You are assigning a click handler to a number of elements, but then deciding what to do by examining all the element afresh. Instead use this inside your handler to only consider the clicked element:

$('div#ttoggle').hide();
$('#btoggle').click( function() {
    var tog = $(this);
    var togp = tog.find("p");    
    if (togp.text() == 'expand article') {
        togp.text('collapse article');
    }
    else {
        togp.text('expand article');              
    }   

    tog.siblings('div#ttoggle').slideToggle("slow");
});

(I don't know what your HTML actually looks like, I took a guess at the siblings.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文