Home » Jquery » javascript – The dynamically added click event gets fired many times

javascript – The dynamically added click event gets fired many times

Posted by: admin February 22, 2020 Leave a comment

Questions:

I am adding a row to the html table on click event of a button. Inside that row, I have 1 cell which contains li element. I have assigned click event for that li element. When I click on li the event gets fired many times, i dont know why…kindly help.

<input id="btnAddRow" type="button" value="Add Row" />
<div id="mainSection">
    <table id="tblList" border="1" cellpadding="1" cellspacing="1">

    </table>
</div>
$(document).ready(function ()
{
    $('#btnAddRow').click(function ()
    {
        $('body').on('click', 'li', function () {
            alert($(this).text());
        })
        var markUp = '<tr><td>1</td><td>2</td><td>3</td><td><li>Hello</li></td></tr>';
        $('table').append(markUp);
        $('table').on('click', 'li', function () {
            alert($(this).text());
        })
    })

});
How to&Answer:

You’re binding the click handler multiple times.

// on each click…
$('#btnAddRow').click(function() {
  // bind a click event on body
  $('body').on('click', 'li', function () {
    alert($(this).text());
  })
  // ...
  // bind a click event on every table
  $('table').on('click', 'li', function () {
    alert($(this).text());
  })
})

As a result, every time your #btnAddRow is clicked you add two additional event handlers, one to body and another to all table elements.