简体   繁体   中英

JQuery displaying only certain id Div

I have a jquery function which displays a div, when an anchor tag with the id toggle_(some unique number) is clicked.

    $("a[id ^= 'toggle']").click(function(event){
        event.preventDefault();
        $("div [id ^= 'replypost']").toggle();
    });
  1. Each of the ids toggle and "replypost end with `_(unique number) for each id so I can separate all of the toggle and replypost divs.

  2. The toggle and reply post divs are displayed through a while() loop.So there are multipe Toggle and replypost divs but each of them have a unique number.

  3. So there is a toggle_1 and a ReplyPost_1 .

I need a way to display only ReplyPost_1 when Toggle_1 is clicked and only ReplyPost_2 when Toggle_2 is clicked, is this possible? If you need me to clear anything up just let me know and thanks for your time.

To display only the post with a matching numeric and hide the others.

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

But if the posts are siblings this is less to write:

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

I think this should do the trick:

$("a[id ^= 'toggle']").click(function(event){
    event.preventDefault();
    $("div [id='replypost_"+$(this).attr('id').replace('toggle_','')+"']").show();
});
$("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();
});

You could use classes to make this alot cleaner, and eliminate the loops.

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

Now you can just listen to a click event on all toggle anchors, get the number from the id, hide all reply divs and show only the matching reply post.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM