开发者

Series of documents displayed with hide/show icons jQuery asp.net

I've got a page with a repeater and a bunch of documents that should be hidden to start and then shown with a p开发者_如何转开发lus sign next to each.

My question is - do I have to assign unique ID to each document DIV to make it be able to toggle hidden and shown?

What's the most code-efficient way to handle this?


Here is a quick example:

http://jsfiddle.net/aaamU/

HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
  <head>
    <title></title>
  </head>
  <body>
    <div id="repeater">
      <div class="document">
        <div class="title">Document 1</div>
          <div class="button"><a href="#">+</a></div>
      </div>
      <div class="document">
        <div class="title">Document 2</div>
        <div class="button"><a href="#">+</a></div>
      </div>
      <div class="document">
        <div class="title">Document 3</div>
        <div class="button"><a href="#">+</a></div>
      </div>
    </div>
  </body>
</html>

CSS

#repeater .document
{
    height: 20px;
    border: 1px solid black;
    width: 200px;
    padding: 10px;
}
.document .title
{
    float:left;
}
.document .button
{
    float:right;
}

JS

$(document).ready(function(){
    $(".title").hide();
    $(".button a").click(function(event){
        $(this).parents(".document").children(".title").toggle();
        event.preventDefault;
    });
});

Here is a Fork with the sliding version:

http://jsfiddle.net/W5QkY/1/


You don't have to assign an ID, you can use their position in the document to identify the correct element.

For example, you have something like this:

<div id="documents">
    <div> ... </div>
    <div> ... </div>
    <div> ... </div>
</div>

You can use jquery like so to trigger individual elements:

$('#documents > div').eq(0).show();

Where the number passed to the eq() method will return the div at that index.


no you dont have to assign them all a different Id. There are many ways to select multiple dom elements with one selector expression

you have a few options

1) you can assign them all the same class and then do $('.className').show()/.hide()

2) you can select them by a css selector related to the page's layout i.e $('#mainContent img').hide() will hide all images inside of a container (prob a div) with id mainContent


You could easily avoid unique id:s on the html tags by using jQuery's traversing capabilities:

<div class="frame">
    [Document title] <a href="#">+</a>
    <div>[document contents, links or whatever go here]</div>
</div>

And the jQuery magic:

$(function() {
    $('.frame a').click(function() {
        var $t = $(this);
        if ($t.html()=='+')
        {
            $t.html('-').next('div').show();
        } else {
            $t.html('+').next('div').hide();
        }
    });
});

You could obviously switch the .show()/.hide() calls to some animation of your choice.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜