JSFiddle - React, Tailwind, and code Playground

by grammar

HTML

<div>
    <h1>Hello Alice</h1>
    <button id="load">Load</button>
    <button id="load-scope">Load With Right Scope</button>
</div>
<div id="modal" class="modal fade">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Modal Title</h4>
            </div>
            <div id="content" class="modal-body">
            </div>
        </div>
    </div>
</div>

JavaScript

$(document).ready(function() {
    //Scope of the function
    
    //$data works the first time, but additional row
    //clicks don't register events
    var $data = expensiveAjaxLoad();
    $('#load').click(function() {
        addRowsAndListeners($data);
        
        $('#content').html($data);
        $('#modal').modal('show');
    });
    
    //Why does this work?
    $('#load-scope').click(function() {
        var $better = expensiveAjaxLoad();
        addRowsAndListeners($better);
        
        $('#content').html($better);
        $('#modal').modal('show');
    });
});

function expensiveAjaxLoad() {    
    var html = [];
    html.push('<table><tbody>');
    html.push('</tbody></table>');
    return $(html.join(''));
}

function addRowsAndListeners($data) {
    var html = [];
    //Rows can vary, don't need to recreate the entire table
    for (var i = 0; i < 5; i++) {
        html.push('<tr><td>Row ');
        html.push((i + 1));
        html.push('</td></tr>');
    }
    $('tbody', $data).html(html.join(''));
    
    //Something here is not binding correctly
    $('tbody td', $data).click(function() {
        alert($(this).html());
    });
}