How to Add the ID Attribute, by Jquery

1

What I want to do is generate ID dynamically through jquery, and it generates it within a for the only problem I have with that is that it always leaves me the last ID that reads and I want each ID to be different.

Code where the ID is generated:

<script>
$(document).ready(function(){
    var PHP_VARS = <?php echo $planta; ?>;
    for (var i=0; i<PHP_VARS; i++) {
        $(".accordion").append("<li class=tabs><div class=paragraph><h1>Accordion</h1><p>Esto es una Pruba.</p></div></li>")
        $('.tabs').attr('id', 'tabs'+i);
}

$(".accordion").click(function() {
   $(".tabs").css("width","300px"); 
});

});
</script>

HTML code:

<body id="cuerpo"> 
  <div class="container">
    <ul class="accordion">        
    </ul>
  </div>
</body>
    
asked by David 23.01.2017 в 16:36
source

1 answer

1

The problem with the question is now here:

for (var i=0; i<PHP_VARS; i++) {
    $(".accordion").append("<li class=tabs><div class=paragraph><h1>Accordion</h1><p>Esto es una Pruba.</p></div></li>")
    $('.tabs').attr('id', 'tabs'+i);
}

And specifically in the part of $('.tabs').attr('id', 'tabs'+i); , since you are using a pretty generic selector and just after adding each tab, the ID of all the tabs will be changed in each pass of the loop. That's why they always end with the last ID.

To solve this, add the ID dynamically:

for (var i=0; i<PHP_VARS; i++) {
    $(".accordion").append("<li class='tabs' id='tabs" + i + "'><div class='paragraph'><h1>Accordion</h1><p>Esto es una Pruba.</p></div></li>")
}

(I have also added quotes to better identify where each field begins and ends)

The problem is here:

$(".accordion").click(function() {
   $(".tabs").css("width","300px"); 
});

What this does is that when you click on an accordion ( $(".accordion").click(...) ) you will select all the tabs and the width will be changed to 300px ( $(".tabs").css("width","300px") ).

It sounds right, but it is not. Why? Because you do not want to select all the tabs and change the width, you want only the tabs that are inside the pulsed accordion. You can get it that way:

$(".accordion").click(function() {
   $(this).find(".tabs").css("width","300px"); 
});

This will select only the tabs that are inside the pressed accordion.

    
answered by 23.01.2017 / 18:06
source