独立显示/隐藏多个元素

我正在使用Andy Langton的show / hide jQuery代码,但看起来代码在同一页面上使用多个切换时有一些故障。

使用多个显示/隐藏时,它不会切换到正确的单词。 它似乎跟踪整个最后的切换而不是每个链接的设置。 换句话说,如果我在第一篇文章中点击“更多”,它将变为“更少”。 如果我在下一篇文章中按下“更多”而不隐藏前一篇文章,它将保留在“更多”,如果我现在尝试隐藏第一篇文章,那么这个词仍然是“较少”。

这是我正在使用的代码:

// 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 (eg 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(''+showText+''); // 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; }); }); 

任何帮助解决这个问题将不胜感激。

马兹

代码中的问题是

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

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

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

看到它在行动

做了一些重写,这更有意义:

 $(function() { var showText = 'MORE ↓', hideText = 'LESS ↑'; $('.toggle').hide().prev('.moree') .append('' + showText + ''); $('a.toggleLink').click(function(e) { e.preventDefault(); var is_visible = $(this).closest('.moree').next('.toggle').is(':visible'); $(this).html(is_visible ? showText : hideText) .parent().next('.toggle').toggle('slow'); }); });​ 

小提琴

代码实际上有一个标志,用于检查所有隐藏DIV的可见性。 需要检查切换的特定div当前是否隐藏

  // change the link depending on whether the element is shown or hidden if( $(this).parent().next(".toggle").is(':visible') ) { $(this).html(showText); } else{ $(this).html(hideText); } 

我已经更新了小提琴来检查这个

更新了jsfiddle

问题是布尔值is_visible。 如果单击第一个链接,则将其设置为false。 如果你点击第二个元素(没有再点击第一个元素),它仍然是假的。