html - How do you assign onclick within for loop in javascript? -


function initnav(){ var cbox=document.getelementsbyclassname('box'); for(var i=0;i<cbox.length;i++){     cbox[i].innerhtml=cbox[i].id;     <!--so far have set captions after setting ids same how want them            appear.-->      <!--what comes next doesn't work.-->     getelementbyid(cbox[i].id).onclick=mclick(cbox[i].id); } 

};

function mclick(id){alert(id);} 

the whole thing in js file, , promptly linked html file.

as planned, buttons should appear , clickable, happening instead 1 of them visible , 1 not working when click on it.

when create lot of div-oriented buttons, wish run loop , able assign each of them clickable instead of writing lines many are.

how assign onclick within loop in javascript?

you're calling function instead of assigning it.

getelementbyid(cbox[i].id).onclick = mclick; 

of course, function receive event argument instead of id. (passing id inside loop huge pain; easiest fix not bother trying.) gets attached element this, convenient:

function mclick() {     alert(this.id); } 

other comments:

  1. you should try not in habit of using innerhtml if you're not assigning string contains known html. saves having care escaping. use textcontent instead.
  2. assigning onclick bit inflexible; can ever assign 1 click handler way, , it's hard notice if accidentally overwrote existing handler. use addeventlistener.
  3. getelementbyid(element.id) should surely equivalent element.
  4. don't use html comments within javascript! :) work for... weird backwards-compatibility reasons. javascript comments either // ... or /* ... */.
  5. best not capitalize function name unless it's supposed constructor; may notice so's highlighting made mclick green, because thinks it's class name.

so i'd end with:

function initnav() {     var cbox = document.getelementsbyclassname('box');     for(var = 0; < cbox.length; i++) {         cbox[i].textcontent = cbox[i].id;         cbox[i].addeventlistener('click', alert_id);     } }  function alert_id(event) {     alert(this.id); } 

Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -