简体   繁体   中英

using getElementsByClassName in for_loop does not work proprly

I have a @foreach loop in my laravel code, in each iteration it shows a table. I want to make a button to show or hide table for each one. I'm using getElementsByClassName to change ID of table tag for each table of iteration, but it works just for first table. Here is my code:

<script>
    var cc = -3;
</script>
    @foreach($last as $t)

        <script>
            $(document).ready(function(){
                cc = cc +1;
                document.getElementsByClassName("table")[cc].setAttribute("id",cc);
                $("#hide").click(function(){
                    $("#"+cc).hide();
                });
                $("#show").click(function(){
                    $("#"+cc).show();
                });
            });
        </script>

        <p>If you click on the "Hide" button, table will desapear.</p>

        <button id ="hide">Hide</button>
            <button id ="show">Show</button>

<table class="table">
......

I found -3 for cc first value by chance. I have know Idea why it is not working. I'm working on it for 2 days but it doesn't work.
Any Idea?

here is a solution that doesn't require a loop on <script> .

@foreach($last as $t)

    <p>If you click on the "Hide" button, table will desapear.</p>

    <button class="hide-button">Hide</button>
    <button class="show-button">Show</button>

    <table class="table">
......
<script>
    $(".hide-button").click(function(){
        $(this).next().next().hide();
    });
    $(".show-button").click(function(){
        $(this).next().show();
    });
</script>

it would have been easier to target the right table if the buttons were grouped in with the table in a <div> (for example)

@foreach($last as $t)

    <p>If you click on the "Hide" button, table will desapear.</p>
    <div>
        <button class="hide-button">Hide</button>
        <button class="show-button">Show</button>

        <table class="table">
    ......
    </div>
@endforeach
<script>
    $(".hide-button").click(function(){
        $(this).parent('div').find('table.table').hide();
    });
    $(".show-button").click(function(){
        $(this).parent('div').find('table.table').show();
    });
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM