javascript - Dynamically created JQUERY buttons defaulting to last element created -
trying create dynamic jquery elements added html page. click on event, create elements array , new elements go different functions. far i've got:
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="content-type" content="text/html; charset=utf-8"> <head> <title>adding buttons dynamically jquery </title> <link type = "text/css" rel="stylesheet" href="jquery-ui.css"> <script type = "text/javascript" src="jquery.min.js"></script> <script type = "text/javascript" src="jquery-ui.min.js"></script> </head> <body> <p>firing off without hitch, html page loaded properly</p> <button id="classchoice">show classes</button> <div id='classsection' style="margin:50px">this our new section test area</div> <script type="text/javascript"> //classes array var classesarray = [ 'spanish','english','french']; var classindex = 0; //button functionality var btn = document.getelementbyid('classchoice'); btn.addeventlistener("click",click2handler,false); //button handler function click2handler(){ alert('clicked button!'); /*code create variable new button */ evaluator(); } //evaluator function function evaluator() { if(classindex<classesarray.length) {//only operate length of classes array for(var = 0; i< classesarray.length;i++) { var wherecreated = jquery('#classsection');//where add var id = 'btn' + classesarray[classindex]; wherecreated.append('<br><button id="' + id + '">' + classesarray[classindex] + '</button>'); jquery('#'+id).button().click(function(){ alert('dynamically added button: '+ id + ' has been clicked...going selector function');alert('id of button clicked: ' + id); selector(id); }); console.log('wherecreated: '+wherecreated+". id: " +id); classindex++; } console.log('classindex: ' + classindex); } } function selector(btnselection) { switch(btnselection) { case 'btnspanish': alert('buenos dias!'); break; case 'btnenglish': alert('howdy partner!');break; case 'btnfrench': alert('oui oui monsieur!');break; default : alert('unhandled exception inside selection'); break; } } </script> </body> </html>
the problem last button created has id evaluated inside selector function, in case btnfrench. how each button pass right id?
you create closure:
(function (id) { jquery('#' + id).button().click(function () { alert('dynamically added button: ' + id + ' has been clicked...going selector function'); alert('id of button clicked: ' + id); selector(id); }); })(id);
the closure defines new scope. necessary because handler isn't called until after loop has finished, not part of scope @ time called, or (in cases) has last possible value loop. (src)
Comments
Post a Comment