当所有人都拥有相同的班级时,如何隐藏/显示跨度?

时间:2011-11-09 15:51:03

标签: jquery toggle show-hide

我有这个HTML代码:

<p>Hello <span class="hide" style="display:none">there</span> jquery</p>
<button class="toggle">Toggle</button>
<p>Hello <span class="hide" style="display:none">You</span> jquery</p>
<button class="toggle">Toggle</button>

使用这个jQuery:

$('.toggle').toggle(
    function() {
        $('.hide').show("slow");},
    function() {    
        $('.hide').hide("slow");}
);

现在,您可以看到两个按钮具有相同的类,并且两个span都具有相同的类。我在这里想要实现的是,当我按下其中一个时,它应该隐藏/显示它上面的跨度。

我已经按照jsFiddle

的方式运行了它

有什么想法吗?

提前致谢

费德里科

5 个答案:

答案 0 :(得分:2)

这应该可以解决问题:

$('.toggle').toggle(
    function() {
        $(this).prev().find('.hide').show("slow");},
    function() {    
        $(this).prev().find('.hide').hide("slow");}
);

答案 1 :(得分:2)

也许

$('button.toggle').click(function() {
    $(this).prev('span').toggle();
});

答案 2 :(得分:0)

将范围的id属性设置为唯一值,然后使用$('#thatid')引用它(将thatid替换为您设置的ID)。

答案 3 :(得分:0)

$('.toggle').toggle(
    function() {
        $(this).prev().show('slow');
    },
    function() {
        $(this).prev().hide('slow');
    }
);

答案 4 :(得分:0)

感谢大家的答案,我发现了另一种方式,这对我需要的东西更好! :)

这是我发现它可能对其他人有帮助的代码。

// Andy Langton's show/hide/mini-accordion - updated 23/11/2009
// Latest version @ http://andylangton.co.uk/jquery-show-hide

// this tells jquery to run the function below once the DOM is ready
$(document).ready(function() {

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

// 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().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);

// 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;

});
});

然后只需使用此表单中的HTML

<a href="#" class="toggleLink">Toggle</a>
<span class="toggle" >there</span>
<a href="#" class="toggleLink">Toggle</a>
<span class="toggle" >You</span>

将类切换添加到要隐藏/显示的任何范围,div或标记,并将类toggleLink添加到父元素

您可以在此处查看jsFiddle

或者在作者的网站上