简体   繁体   中英

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

As opposed to setting individual functions to each element's click event, I would like to iterate elements and assign based on id or whatever?

document.getElementById('measure').onclick = function() { clickMe(1); };

How would I approach this?

In the past I've done something along these lines:

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

...where selector is a class selector, eg .my-class . Within the callback passed to each you can get at other properties of the selected elements, eg id etc. If you add that class to the elements you'd like to set a click function and call setClickOnElements('.my-class'); on load, you should be good to go!

EDIT: The above uses jQuery. If you're restricted to pure Javascript, you could use one of the methods described in John Resig's post on implementations of getElementByClass : http://ejohn.org/blog/getelementsbyclassname-speed-comparison/

Here's an example (using Dustin Diaz's method from 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|$)");
    for (i = 0, j = 0; i < elsLen; i++) {
        if ( pattern.test(els[i].className) ) {
            classElements[j] = els[i];
            j++;
        }
    }
    return classElements;
}

var setClickOnElements = function(className) {
    var elements = getElementsByClass(className);
    for (var i = 0; i < elements.length; i++) {
        var element = elements[i];
        element.onclick = function(event) {
            // click behaviour here
        };
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM