javascript - Trigger click event on click of other element in a loop -
i have requirement have fire click event on table header on click of other table header (2 different tables), trigger not fired on table when in loop. although if hardcode , bind trigger individual element, works.
currently, js looks this:
var outsideheaders = $("#header th"); var tableheaders = $(".datatable th"); for(var cnt = 0; cnt< outsideheaders.length; cnt++) { $(outsideheaders[cnt]).bind('click',function(){ $(tableheaders[cnt]).trigger('click'); }); }
please provide solution this!
updated:
how code looks now:
var outsideheaders = $("#header th"); var tableheaders = $(".datatable th"); for(var cnt = 0; cnt< outsideheaders.length; cnt++) { (function(headercnt){ $(outsideheaders[headercnt]).bind('click',function(){ $(tableheaders[headercnt]).trigger('click'); }); })(cnt); }
the value of cnt
inside click event handler function going equal last value in for
loop (in case, whatever header.length
when code executed) due way scoping in javascript works. need use closure maintains value specific iteration:
$(document).ready(function() { var outsideheaders = $("#header th"); var tableheaders = $(".datatable th"); for(var cnt = 0; cnt < outsideheaders.length; cnt++) { (function(headercount) { $(outsideheaders[headercount]).bind('click',function(){ $(tableheaders[headercount]).trigger('click'); }); })(cnt); } });
note i've wrapped code in $(document).ready()
call. ensure elements exist when try select them.
Comments
Post a Comment