1

I have HTML file with JavaScript code inside, which should add new cell to table with button when user click on any other buttons in document with class name addCell:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $('.addCell').click(function() {
        addNewRow(this);
    });   
});   
function addNewRow(Sender)
{
    var tbl = document.getElementById('testt');
    var r = tbl.insertRow(tbl.rows.length);
    var c1 = r.insertCell(0);
    c1.className = "addCell";
    c1.innerHTML = "<button class=\"addCell\">New cell by " + Sender.innerHTML + "</button>";
} 
</script>
</head>
<body>
<table border="1" id="testt">
    <tr>
        <td><button class="addCell">AddNew 1</button></td>
    </tr>
    <tr>
        <td><button class="addCell">AddNew 2</button></td>
    </tr>
</table>
</body>
</html>

When I click on the buttons with class addCell, saved in HTML document in design time, my code work well done.

But when I click on new buttons, added by my script in run time, with same class name, nothing happens.

I use class name, for add buttons by jQuery, onclick method, because, number of buttons is unlimited, and writing to all buttons, attribute onclick with name of function, is not the best way to optimize personal code.

What I make incorrect? Please help me to change this code for well and right work.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

1 Answers1

0

I think you need to use event delegation for dynamic appended elements https://learn.jquery.com/events/event-delegation/

Instead of

$('.addCell').click(function() {
    addNewRow(this);
}); 

try this

$(document).on('click','.addCell',function(){
    foo();
});
xlKD
  • 169
  • 1
  • 3
  • 13