-2

https://i.stack.imgur.com/3nrr5.png

what is my mistake ? why this click function is did not work ? i made this function without each loop, then that function working properly, but why did not work this place ?

<html>
<head>
    <title> NG - REPEAT </title>
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
</head>
<body>
    <table border="1">
        <thead>
            <tr>
                <th>ID</th>
                <th>NAME</th>
                <th>VERSION</th>
                <th>PRICE</th>
                <th>ACTION</th>
            </tr>
        </thead>
        <tbody class="tr">

        </tbody>
    </table>
    <script>

        $(document).ready(function()
        {
            $.ajax({
                url:'data.json',
                dataType:'json',
                success: function(data)
                {
                        console.log(data);
                    $.each(data.product, function(name, value)
                    {
                        var result = '<tr><td>'+name+'</td><td>'+value.name+'</td> <td>'+value.version+'</td> <td>'+value.price+'</td><td><button id="btn">Load</button></td></tr>';
                        $(".tr").append(result);
                    });
                }
            });

            $("button").click(function(){
                alert("hi");
            });
        });
    </script>

</body>

1 Answers1

1

You need to add your event listener after your loop creating buttons, so do something like :

$(document).ready(function()
        {
            $.ajax({
                url:'data.json',
                dataType:'json',
                success: function(data)
                {
                        console.log(data);
                    $.each(data.product, function(name, value)
                    {
                        var result = '<tr><td>'+name+'</td><td>'+value.name+'</td> <td>'+value.version+'</td> <td>'+value.price+'</td><td><button id="btn">Load</button></td></tr>';
                        $(".tr").append(result);
                    });
                    $("button").click(function(){
                     alert("hi");
                    });
                }
            });


        });
Dylan KAS
  • 4,840
  • 2
  • 15
  • 33