admin管理员组

文章数量:1429741

I had 10 div with name sample

<div name="sample">div1</div>
<div name="sample">div2</div>
<div name="sample">div3</div>
<div name="sample">div4</div>
<div name="sample">div5</div>
<div name="sample">div6</div>
<div name="sample">div7</div>
<div name="sample">div8</div>
<div name="sample">div9</div>
<div name="sample">div10</div>
<input type="button" id="display" value="display">

once display button in clicked i need to display two div

first click: display div1 and div2 [other div are none]

second click: display div3 and div4 [other div are none]

etc...

How to do this with jquery

I had 10 div with name sample

<div name="sample">div1</div>
<div name="sample">div2</div>
<div name="sample">div3</div>
<div name="sample">div4</div>
<div name="sample">div5</div>
<div name="sample">div6</div>
<div name="sample">div7</div>
<div name="sample">div8</div>
<div name="sample">div9</div>
<div name="sample">div10</div>
<input type="button" id="display" value="display">

once display button in clicked i need to display two div

first click: display div1 and div2 [other div are none]

second click: display div3 and div4 [other div are none]

etc...

How to do this with jquery

Share Improve this question asked Jan 25, 2011 at 15:19 Mohan RamMohan Ram 8,46325 gold badges85 silver badges131 bronze badges 2
  • I dont know how to do this in cyclic way @anand – Mohan Ram Commented Jan 25, 2011 at 15:24
  • what do you mean by "cyclic"??? – tster Commented Jan 25, 2011 at 15:25
Add a ment  | 

3 Answers 3

Reset to default 6
$('#display').bind('click', function() {
   var $divs   = $('div'),
       offset  = 0;

   return function() {
       $divs.hide().slice(offset, offset+2).show();
       offset += 2;

       if( offset === 10 )
           offset = 0;
   };
}()).click();

Demo: http://www.jsfiddle/yNABj/3/

With this script, each time the button is clicked, 2 divs are shown and the others are hidden:

$('#display').click((function() {
    var divs = $('div[name="sample"]');
    var offset = 0;
    return function() {
        if (offset >= divs.length) offset = 0;
        divs.hide().slice(offset, offset+2).show();
        offset += 2;
    };
})());

Each time the button is clicked, the two next divs are shown, and the others are hidden. And it restarts once all divs have been shown.

(This has been partially inspired by jAndy's solution while he deleted his answer)

You can use :nth-child

$('div[name=sample]:nth-child(1)').show();
$('div[name=sample]:nth-child(3)').show();

then

$('div[name=sample]:nth-child(2)').show();
$('div[name=sample]:nth-child(4)').show();

本文标签: javascriptTo display div dynamicallyStack Overflow