2013-02-20 70 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(); 
});