jquery effect does not work because of relatives

Asked

Viewed 57 times

0

I need to open the id="SUB_1" when I click the <li id="B1">Botão 1</li> and do the same when I click on <li id="B1">Botão 2</li> open the id="SUB_1" that this below the q button was clicked. And do the msm with the 3 too, but only with that jquery that I put at the end.

$(function(){
   $(".Principal").click(function(){
      $(this). ???
   });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ol class="Principal">
        <li id="B1">Botão 1</li>
    </ol>

    <ol id="SUB_1">
        <li id="A1">1</li>
        <li id="A2">2</li>
        <li id="A3">3</li>
    </ol>


    <ol class="Principal">
        <li id="B1">Botão 2</li>
    </ol>

    <ol id="SUB_1">
        <li id="A4">4</li>
        <li id="A5">5</li>
        <li id="A6">6</li>
    </ol>


    <ol class="Principal">
        <li id="B1">Botão 3</li>
    </ol>

    <ol id="SUB_1">
        <li id="A7">7</li>
        <li id="A8">8</li>
        <li id="A9">9</li>
    </ol>
  • Some considerations: unlike classes, id is used for only one element. Thus, you should redesign button ids to B1, B2, B3, bx and list ids to Sub1, sub2, sub3, etc.

  • In Jquery, Event Listener (click) could be relative to the id of the button clicked (e.g., #B1) instead of the parent class.

2 answers

1


It is incorrect to use several ids for more than one element. But as you are picking up the click by class .Principal, you can reference the element that comes just below with .next(). For illustration only, I created a class to visualize the effect:

$(function(){
   $(".Principal").click(function(){
      $(this).next().addClass("red");
   });
});
.red{
   color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ol class="Principal">
   <li id="B1">Botão 1</li>
</ol>

<ol id="SUB_1">
   <li id="A1">1</li>
   <li id="A2">2</li>
   <li id="A3">3</li>
</ol>

<ol class="Principal">
   <li id="B1">Botão 2</li>
</ol>

<ol id="SUB_1">
   <li id="A4">4</li>
   <li id="A5">5</li>
   <li id="A6">6</li>
</ol>

<ol class="Principal">
   <li id="B1">Botão 3</li>
</ol>

<ol id="SUB_1">
   <li id="A7">7</li>
   <li id="A8">8</li>
   <li id="A9">9</li>
</ol>

But I recommend you fix your code by taking out these various ids. You can use class instead of id.

  • Thank you, your reply helped me a lot.

0

$(".B1").click(function(){
    $('.B1')($(this).parents('ol').next().slideToggle(200));
});

I got it that way.

Thanks to everyone who tried to help and who gave vlw tips

Browser other questions tagged

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