2013-02-20 39 views
0

我有一個jQuery的函數,它顯示一個div,當一個帶有id toggle_(某個唯一編號)的錨標籤被點擊時。只顯示某個ID的JQuery Div

$("a[id ^= 'toggle']").click(function(event){ 
     event.preventDefault(); 
     $("div [id ^= 'replypost']").toggle(); 
    }); 
  1. 的id toggle"replypost端與`_(唯一號碼)每個ID的每個,所以我可以分離所有的肘節和replypost的div。

  2. 肘和回覆帖子的div通過一個 而()顯示loop.So有multipe Togglereplypost的div,但他們每個人都有一個唯一的編號。因此有toggle_1ReplyPost_1

我需要一種方法來只顯示ReplyPost_1點擊Toggle_1當且僅當ReplyPost_2點擊Toggle_2,這可能嗎?如果你需要我清除任何事情,只需告訴我,謝謝你的時間。

+0

那麼,你有三個幾乎相同的答案。我認爲你現在應該知道該怎麼做... – 2013-02-20 23:55:38

+0

是的,他們工作感謝 – 2013-02-20 23:58:11

+1

任何時候我看到這些'something_#'元素ID方案之一,我通常會想到的情況下,用戶在思考一箇舊的JavaScript範例和沒有真正採用jQuery做事的方式。如果你能顯示你的實際源碼輸出,我敢打賭你可以得到很好的建議,如何完全消除該ID號碼方案。 – 2013-02-21 00:00:52

回答

1

僅顯示匹配數字的帖子並隱藏其他數字。

$("a[id^='toggle']").click(function(event){ 
    event.preventDefault(); 
    $("[id^='replypost']").hide(); 
    $("#replypost_" + this.id.replace('toggle_', '')).show(); 
}); 

但如果帖子是兄弟,這是少寫:

$("a[id^='toggle']").click(function(event){ 
    event.preventDefault(); 
    $("#replypost_" + this.id.replace('toggle_', '')).show().siblings().hide(); 
}); 
1

我想這應該做的伎倆:

$("a[id ^= 'toggle']").click(function(event){ 
    event.preventDefault(); 
    $("div [id='replypost_"+$(this).attr('id').replace('toggle_','')+"']").show(); 
}); 
+0

謝謝你的工作,你可以解釋一點,所以我明白,但非常感謝。 – 2013-02-20 23:56:45

+1

使用$(this).attr('id'),我得到了clicked元素的id(讓我們說toggle_2)。然後使用替換函數的字符串我刪除toggle_,所以我得到了2.我希望這個解釋就足夠了。但如果不是,請讓我知道。 – haitaka 2013-02-21 00:00:57

1
$("a[id^='toggle']").click(function(event){ 
    event.preventDefault(); 
    // grab the index of the clicked element from it's ID 
    var index = $(this).attr('id').match(/\d+$/)[0] 
    // identify the thing to toggle uniquely, based on the grabbed index 
    $("div#replypost_"+index).toggle(); 
}); 
1

你可以使用類做這很好的清潔劑,並消除循環。

<a id="toggle_1" class="toggle" /> 
<div id="replyPost_1" class="reply-post" /> 

現在你可以只聽click事件上所有切換錨,您可以通過ID的數量,隱藏所有回覆的div,僅顯示匹配的答覆後。

$(".toggle").click(function(e) { 
    var num = $(this).attr("id").split("_")[1]; 
    $(".reply-post").hide(); 
    $("replyPost_"+num).show(); 
});