JQuery - Attenuation of various In and Out On Button Click elements

I am trying to create several buttons that create a window, depending on which button is pressed. I do this by providing each box with its own class and passing an argument to the function to determine which field is intended for targeting. Then I assign this function to each onclick attribute button on the page (I know that I should probably add an event handler to a separate file). Here is the function:

var show = function(boxNumber){
    if($(this).hasClass('shown')){
       $(this).removeClass('shown');
       $(this).html('Show');
       $('.box'+boxNumber).fadeOut(1000);
      }
    else{
       $(this).html('Hide');
       $(this).addClass('shown');
       $('.box'+boxNumber).fadeIn(1000);
      }
 };

html:

<span onclick="show(1)">Box 1</span>
<div class="box1"></div>

etc. for more boxes

However, this feature does not work. Firstly, this keyword does not look like button targeting, because the button’s html does not change when clicked. However, when I replace this keyword with a button class, it works fine.

Secondly, the function freezes in the boxes in order, but then does not hide them if I press the button again.

, ! .

+5
2

1 ( jQuery):

- jQuery . jQuery , ? :

jsFiddle

<span>Box 1</span>
<div class="box1"></div><br/>
<span>Box 2</span>
<div class="box2"></div><br/>
<span>Box 3</span>


$('span').click(function () {
    var boxNumber = $(this).index('span') + 1;
    if ($(this).hasClass('shown')) {
        $(this).removeClass('shown');
        $(this).html('Show');
        $('.box' + boxNumber).fadeIn(1000);
    } else {
        $(this).html('Hide');
        $(this).addClass('shown');
        $('.box' + boxNumber).fadeOut(1000);
    }
});

.. , , , fadeTo() .

2 ():

, onclick , , :

jsFiddle

<span onclick="show(1,this)">Box 1</span>
<div class="box1"></div><br/>
<span onclick="show(2,this)">Box 2</span>
<div class="box2"></div><br/>
<span onclick="show(3,this)">Box 3</span>


function show(boxNumber, elem) {
    $this = $(elem);

    if ($this.hasClass('shown')) {
        $this.removeClass('shown');
        $this.html('Show');
        $('.box' + boxNumber).fadeIn(1000);
    } else {
        $this.html('Hide');
        $this.addClass('shown');
        $('.box' + boxNumber).fadeOut(1000);
    }
};
+3

http://jsfiddle.net/fVENv/5/

, , - jquery , ( fade).

html:

<p>Box 1</p>
<div></div><br/>
<p>Box 2</p>
<div></div><br/>
<p>Box 3</p>
<div></div><br/>

jquery:

$('p').append('<span class="show">Show</span><span class="hide">Hide</span>');
$('div').hide();
$('p').click(function () {
    $('p').click(false);
    $(this).toggleClass('hidden').next('div').fadeToggle(function(){
    $('p').click(true);
    });
});

css:

div {
    width:50px;
    height : 50px;
    background: red;
}
p {cursor:pointer;}
span { padding: 5px; margin-left:5px;}
p.hidden > .hide, p > .show  { display:inline }
p > .hide, p.hidden > .show { display: none; }
+1

All Articles