Javascript onClick event in all cells

前端 未结 8 2237
忘了有多久
忘了有多久 2020-12-20 17:09

I\'m learning JavaScript and I\'ve not that much experience. But I\'m making a HTML table and I want to add in every table cell () a onClick event.

相关标签:
8条回答
  • 2020-12-20 17:48

    if you have access to jquery, do this

    $('#1 td').click(function(){
    
    });
    
    0 讨论(0)
  • 2020-12-20 17:54

    You may try this too (using event delegation)

    window.onload = function(){
        document.getElementById('tbl1').onclick = function(e){
            var e = e || window.event;
            var target = e.target || e.srcElement;
            if(target.tagName.toLowerCase() ==  "td") {
                alert(target.innerHTML);
            }
        };
    };
    

    EXAMPLE.

    Using jQuery

    $(function(){
        $('#tbl1').on('click', 'td', function(){
            alert($(this).html());
        });
    });
    

    EXAMPLE.

    0 讨论(0)
提交回复
热议问题