为什么 jquery的append方法填充的元素,其的点击事件无法被监听

发布时间:2024-07-25 18:03:47    发布者:文昌文城莱奥网络技术工作室    浏览次数:200

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dynamic Element Click Event Listener</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <table style="width:98%;margin: 0 auto; color: #689F38;border: none;line-height: 28px;">
        <tbody>
            <tr>
                <td style="border: none;width: 25%; word-break: break-all; text-align: center;" id="positionAForecastNumbers">
                    <!-- Initial font elements -->
                </td>
                <td style="border: none;width: 25%;" id="positionBForecastNumbers"></td>
                <td style="border: none;width: 25%;" id="positionCForecastNumbers"></td>
                <td style="border: none;width: 25%;" id="positionDForecastNumbers"></td>
            </tr>
        </tbody>
    </table>

    <button id="addFontElement">Add Font Element</button>

    <script>
        $(document).ready(function(){
            // Use event delegation to listen for click events on font elements within #positionAForecastNumbers
            $('#positionAForecastNumbers').on('click', 'font', function(){
                var number = $(this).text();
                var index = $(this).data('position_a_number_index');
                alert('You clicked on number: ' + number + ', at index: ' + index);
            });

            // Add a new font element dynamically when the button is clicked
            $('#addFontElement').on('click', function(){
                var newIndex = $('#positionAForecastNumbers font').length;
                $('#positionAForecastNumbers').append('<font data-position_a_number_index="' + newIndex + '">' + (newIndex + 1) + '</font>');
            });
        });
    </script>
</body>
</html>