javascript - How do you dynamically assign a function to an element's onclick event? -


as opposed setting individual functions each element's click event, iterate elements , assign based on id or whatever?

document.getelementbyid('measure').onclick = function() { clickme(1); }; 

how approach this?

in past i've done along these lines:

var setclickonelements = function(selector) {     $(selector).each(function() {         $(this).click(function(event) {             // behaviour on click         });     }); }; 

...where selector class selector, e.g. .my-class. within callback passed each can @ other properties of selected elements, e.g. id etc. if add class elements you'd set click function , call setclickonelements('.my-class'); on load, should go!

edit: above uses jquery. if you're restricted pure javascript, use 1 of methods described in john resig's post on implementations of getelementbyclass: http://ejohn.org/blog/getelementsbyclassname-speed-comparison/

here's example (using dustin diaz's method http://www.dustindiaz.com/getelementsbyclass):

var getelementsbyclass = function(searchclass,node,tag) {     var classelements = new array();     if ( node == null )         node = document;     if ( tag == null )         tag = '*';     var els = node.getelementsbytagname(tag);     var elslen = els.length;     var pattern = new regexp("(^|\\s)"+searchclass+"(\\s|$)");     (i = 0, j = 0; < elslen; i++) {         if ( pattern.test(els[i].classname) ) {             classelements[j] = els[i];             j++;         }     }     return classelements; }  var setclickonelements = function(classname) {     var elements = getelementsbyclass(classname);     (var = 0; < elements.length; i++) {         var element = elements[i];         element.onclick = function(event) {             // click behaviour here         };     } }; 

Comments

Popular posts from this blog

google api - Incomplete response from Gmail API threads.list -

Installing Android SQLite Asset Helper -

Qt Creator - Searching files with Locator including folder -