简体   繁体   中英

Javascript- Adding click event to dynamically generated cell of table

addEventListener() not working ?

var mytable = document.getElementById('GridTable');

for (var r = 0; r <rows; r++) 
{
    var row = mytable.insertRow(r);
    for (var c = 0; c <cols; c++)
    {

        var cell=row.insertCell(c);
        cell.id='td'+nn;
        //alert(cell.id);
        cell.innerHTML='&nbsp';
        cell.className="dynamic";
        cell.addEventListener("click", function() {bcolor1('red',cell.id);});
        nn++;
    }

}

You need to use event delegation to achieve this.

With Javascript , you can do it this way:

document.querySelector('element').addEventListener('click', function(event) {      
    // on click action here..
});

With jQuery , you can do it this way:

$(document).on("click", "element", function(){
  // on click action here..
});

Learn more: Understanding Event Delegation | jQuery

You can use on() function to achieve event delegation.

This way, you can select every dynamicaly added element with class .dynamic

$(document).on('click', '.dynamic', function() {
    var that = $(this);
    that.css({'background-color': 'red'});
    // do your stuff here ..
});

I got the following solution and it is working fine .

 var mytable = document.getElementById('GridTable');
 for (var r = 0; r <trow; r++) 
    {
        temp=noc;
        var row = mytable.insertRow(r);
        for (var c = 0; c <tcol; c++)
        {
            cell=row.insertCell(c);
            cell.id='td'+temp;
            cell.style.width =cwidth;
            cell.style.height =cheight;
            //alert(cell.id);
            //cell.innerHTML='&nbsp;';
            cell.className="dynamic";

            with ({ n: cell.id }) 
            {
                cell.onclick = function()
                {
                        bcolor1('red',n);
                };
                cell.onmousemove=function()
                {
                    bcolor('red',n);
                }   
            }                                                         
            temp++;
        }
        noc=noc-tcol;
    } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM