2012-10-17 63 views
1

下面的代碼:http://jsfiddle.net/t2nite/KCY8g/隱藏一切,但

我試圖得到SHOW按鈕下方的HIDE/SHOW ALL按鈕,如果你按下一個按鈕,它會顯示它的文本並隱藏其他文本。

我用這個代碼,但只要我打顯示在任何按鈕,它會顯示和隱藏自身。

$(".show").click(function() { 
    $(this).parent().find("p").show(200); 
    $("p").not(this).hide(200); 
});​ 

幫助。

+1

'this'並不是指一個'p'元件,所以'$( 「P」)。未(這)'相當於'$( 'P')'和將選擇頁面上的所有「p」元素。你想要的是首先獲得對應於按鈕的「p」元素的引用。 –

回答

3

你的問題是,this在展示功能不是<p>這是按鈕。

$(".show").click(function() { 
    var $thisP = $(this).parent().find("p") 
    $thisP.show(200); 
    $("p").not($thisP).hide(200); 
});​ 

http://jsfiddle.net/KCY8g/11/

1

更改顯示的代碼是這樣的:

$(".show").click(function() { 
    var container = $(this).closest(".itsawrap"); 
    $(".itsawrap").not(container).find("p").hide(200); 
    container.find("p").show(200); 
});​ 

工作演示在這裏:http://jsfiddle.net/jfriend00/6ypRz/

此作品在容器級別,所以你可以在需要的容器進行操作。

+0

棘手和它的作品,但它只隱藏問題。 。 $( 「P」)不(本).hide(200); <---「這個」不是你的「p」,它是「按鈕」。非常無用。 –

+0

@MaximeMorin - 我用更完整的解決方案更新了我的答案。 – jfriend00

+0

非常感謝你,我不認爲訂單在編寫腳本時非常重要。 – t2nite

2

jsFiddle Demo

基本上你想隱藏的所有「itsawrap P」,除了目前的一個領域。

$(".show").click(function() { 
    var _p = $(this).parent().find('p'); 
    // maybe even do: $(this).closest('.itsawrap').find('p'); 
    // (if you ever think you'll wrap any of these things in other divs/etc 

    _p.show(200); 
    $('.itsawrap p').not(_p).hide(); 
});​ 
0

喜歡這個?

$("#btn").click(function() { 
    var oneshow = false; 
    $(".para2, .para3, .para4").each(function() { 
     if ($(this).is(":visible")) { 
      oneshow = true; 
     } 
    }); 
    if (oneshow == true) { 
     $(".para2, .para3, .para4").hide(200); 
    } else { 
     $(".para2, .para3, .para4").show(200); 
    } 
}); 

$(".hide").click(function() { 
    $(this).parent().find("p").hide(200); 
}); 

$(".show").click(function() { 
    var p = $(this).parent().find("p"); 
    $(p).show(200); 
    $(parent).not(p).hide(200); 
});​ 
0

問題出在this

$(".show").click(function() { 
    var p = $(this).parent().find("p"); 
    p.show(200); 
    $("p").not(p).hide(200); 
});​ 
0

一個最簡短的方式:

$(".show").click(function(e) { 
    $("p").not($(this).parent().find("p").show(200)).hide(200); 
}); 

jsfiddle

0

錯誤是父 「這」 按鈕,因此$( 「P」)沒有(這個。 ).hide(200);說除了你的按鈕,所有的p都是p的。

$(".show").click(function() { 
    var parent = $(this).parent(); 
    $(".itsawrap").not(parent).find('p').hide(200); 
    parent.find('p').show(200); 
});​ 

http://jsfiddle.net/renekoch/KCY8g/17/