简体   繁体   中英

Adding onclick event to newly created table header in javascript, but the onclick function is added to all th's on the page, not just the one I want

I'm generating a table in js and using a function as follows for some of the headers:

function generateTableHeader(table) {
    var tr = document.createElement('tr');

    var th = document.createElement('th');

    th.onclick = function(){
        toggleHidden("hide_header_" + table_count);
    };

    th.appendChild(document.createTextNode(key));
    tr.appendChild(th);    


    table.appendChild(tr);
}

My toggle hidden function just hides all elements of the class "hide_header_{some number}". It works fine.

The problem is, I call this generateTableHeader function several times, creating headers for multiple tables - each time it's called table_count (global variable) is incremented and I expected this function to hide only the class of elements with the number it has when the onclick event is created. Instead, whenever I click on any of the headers, they always hide the last element created.

The function is called 4 times to create 4 table headers in 4 different tables - each has a column of td's with the correct class name (ie "hide_header_1", "hide_header_2" and so on). When I click on the first header, the fourth table column is hidden/show. When I click the second, third, or fourth, still only the fourth column is hidden/show. I want each th click to hide only the td's in that table.

It's as if the th onclick event I am creating is being overwritten each time I call this function, not sure why. Any ideas?

Any help would be appreciated!

This is a closure issue, you are using the same variable in all your click handlers. Instead you can use a local variable with the value of the global variable at the time the set the click event.

function generateTableHeader(table) {
    var tr = document.createElement('tr');

    var th = document.createElement('th');

    var local_table_count = table_count;
    th.onclick = function(){
        toggleHidden("hide_header_" + local_table_count);
    };

    th.appendChild(document.createTextNode(key));
    tr.appendChild(th);    


    table.appendChild(tr);
}

I think the answer probably lies within your own description. table_count is a global variable. Every time you increment it the reference that all of your event listeners are using in the line:

th.onclick = function(){
    toggleHidden("hide_header_" + table_count);
};

are having the reference updated.

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