Javascript attach event to class name

前端 未结 1 1832
野的像风
野的像风 2021-02-04 13:10

If I have 10 items, with the class name keyword:

How can I attach an event, for example

相关标签:
1条回答
  • 2021-02-04 13:31

    You should delegate the event. Try this:

    if (document.body.addEventListener)
    {
        document.body.addEventListener('click',yourHandler,false);
    }
    else
    {
        document.body.attachEvent('onclick',yourHandler);//for IE
    }
    
    function yourHandler(e)
    {
        e = e || window.event;
        var target = e.target || e.srcElement;
        if (target.className.match(/keyword/))
        {
            //an element with the keyword Class was clicked
        }
    }
    

    You can read more on event delegation on quirksmode.com. AFAIK, this is the best way of achieving what you're trying to achieve. This is how all the major libs (prototype, jQuery, ...) work behind the scenes

    Update:

    Here's the fiddle, it contains some more explanation. An interesting reference is this page. It helped me understand the way IE and W3C events differ and, crucialy, it helped me understand the value, and countless benefits of Event Delegation

    0 讨论(0)
提交回复
热议问题