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:
- you should try not in habit of using innerhtmlif you're not assigning string contains known html. saves having care escaping. usetextcontentinstead.
- assigning onclickbit inflexible; can ever assign 1 click handler way, , it's hard notice if accidentally overwrote existing handler. useaddeventlistener.
- getelementbyid(element.id)should surely equivalent- element.
- don't use html comments within javascript!  :)  work for...  weird backwards-compatibility reasons.  javascript comments either // ...or/* ... */.
- best not capitalize function name unless it's supposed constructor; may notice so's highlighting made mclickgreen, 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
Post a Comment