How to use this!

Asked

Viewed 95 times

4

I need each button when clicked yellow and the others back to normal...:

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

Jsfiddle

3 answers

6


In your case, missed to iterate over the buttons, you iterou only in the div#botoes, needs to iterate on the children of this div that encompasses the buttons.

That way your code would be:

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

Jsfiddle of that solution.

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

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

Jsfiddle of that solution.

  • There’s a Fiddle I can play with?

  • I did it once but I closed it, I’ll redo it and put it here.

  • Ready @Ciganomorrisonmendez, includes both.

  • It was cool. + 1.

5

Based on your Fiddle, made another.

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

The code went like this:

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

That is, for each class .botoes, the behavior is monitored .click. By clicking, remove the class from all buttons botaoativo (which turns the button yellow), and adds botaoativo only on the button clicked (where I use the this).

  • The .click will monitor equally all applied selectors, regardless if it is class, ID, tag, pseudo class, find, Children, Parent or any other selection function, it will make no distinction at all as long as it receives the(s) element(s)...

  • Yes. So, .botoes. It’s brighter in the Fiddle.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.