How to use this!

4

I need each button when clicked to turn yellow and the others return to normal ... follow the code and the fiddle:

$( "#botoes" ).each(function() {
    $(this).click(function() {
        $(".botaoativo").removeClass('botaoativo');
        $(this).addClass('botaoativo');
    });
 });

JSFiddle

    
asked by anonymous 21.09.2014 / 21:56

3 answers

6

In your case, it failed to iterate over the buttons, you iterated only in div#botoes , need to iterate over the children of that div that encompasses the buttons.

That way your code would look like:

$("#botoes div").each(function() {
    $(this).click(function() {
        $(".botaoativo").removeClass('botaoativo');
        $(this).addClass('botaoativo');
    });
});

JSFiddle of that solution.

Another way would be to iterate over the children, regardless of what they are, through the function children :

$("#botoes").children().each(function() {
    $(this).click(function() {
        $(".botaoativo").removeClass('botaoativo');
        $(this).addClass('botaoativo');
    });
});

JSFiddle for this solution.

    
21.09.2014 / 22:02
5

Based on your Fiddle, I made another .

.click is an event that should monitor the buttons by class to be efficient. That is, I set class to all its buttons and removed the div from outside, which had no use in the example.

The code looks like this:

$(".botoes").click(function() {
    $(".botoes").removeClass('botaoativo');
    $(this).addClass('botaoativo');
});

That is, for each class .botoes , behavior .click is monitored. When you click, remove the botaoativo (leaving the yellow button) from all buttons, and add botaoativo to the clicked button (where I use this ).

    
21.09.2014 / 22:01
3

In these situations many forget that you can group multiple selectors in both CSS and Jquery:

Jquery:

$('#botao1, #botao2, #botao3, #botao4').click(function () {
    if ($(this).hasClass('botaoativo')) return false; // presumindo que tenha mais comandos que não devem ser re-executados em caso de click no botão ativo
    $(".botaoativo").removeClass('botaoativo');
    $(this).addClass('botaoativo');
});

CSS:

#botao1, #botao2, #botao3, #botao4 {
    margin-left: 10px;
    width: 10px;
    float: left;
    height: 10px;
    background-color: #333333;
    cursor: pointer;
    position: relative;
    z-index: 10;
}
#botao1 {
    margin-left: 0;
}

See working on JSFiddle

    
21.09.2014 / 22:53