独立显示/隐藏多个元素 [英] Show/hide multiple elements independently

查看:83
本文介绍了独立显示/隐藏多个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Andy Langton的show/hide jQuery代码,但是当您在同一页面上使用多个切换时,该代码看起来有些毛刺.

I am using Andy Langton's show/hide jQuery code but looks like the code has some glitches when you use multiple toggles on the same page.

使用多个显示/隐藏"时,不会切换到正确的单词.它似乎是跟踪最后一个切换的整体,而不是每个链接的设置.换句话说,如果我在第一篇文章上单击更多",它将更改为少".如果我在不隐藏上一篇文章的情况下在下一篇文章上按更多",则它将停留在更多",而如果我现在尝试隐藏第一篇文章,则该单词仍为少".

When using multiple Show/Hide it would not toggle to the correct word. It seemed to track the last toggle overall rather than the setting for each link. In other words, if I clicked 'More' on the first article, it would change to 'Less'. If I pressed 'More' on the next article without hiding the previous, it would stay at 'More', and if I try and hide the first article now, that word remained 'Less'.

这是我正在使用的代码:

This is the code I am using:

// Andy Langton's show/hide/mini-accordion - updated 23/11/2009
// Latest version @ http://andylangton.co.uk/jquery-show-hide
$(document).ready(function() {

    // choose text for the show/hide link - can contain HTML (e.g. an image)
    var showText='MORE ↓';
    var hideText='LESS ↑';

    // initialise the visibility check
    var is_visible = false;

    // append show/hide links to the element directly preceding the element with a class of "toggle"
    $('.toggle').prev('.moree').append('<a href="#" class="toggleLink">'+showText+'</a>');

    // hide all of the elements with a class of 'toggle'
    $('.toggle').hide();

    // capture clicks on the toggle links
    $('a.toggleLink').click(function() {

    // switch visibility
    is_visible = !is_visible;

    // change the link depending on whether the element is shown or hidden
    $(this).html( (!is_visible) ? showText : hideText);
    //$(this).html( ($(this).html() == hideText) ? showText : hideText);

    // toggle the display - uncomment the next line for a basic "accordion" style
    //$('.toggle').hide();$('a.toggleLink').html(showText);
    $(this).parent().next('.toggle').toggle('slow');

    // return false so any link destination is not followed
    return false;

    });
    });

任何帮助解决此问题的方法,将不胜感激.

Any help to fix this would be appreciated.

Marz

推荐答案

代码中的问题是

使用相同的var is_visible来切换元素.

Use of same var is_visible to toggle elements.

每次切换内容的可见性时,我们都必须检查相应div的可见性.

We have to check visibility of corresponding div every time we toggle the visibility of content.

    $(this).html( ($(this).parent().next('.toggle').is(":visible")) ? showText : hideText);

查看实际效果

这篇关于独立显示/隐藏多个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆