最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript attach event to class name - Stack Overflow

programmeradmin1浏览0评论

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

<div class="keyword"></div>

How can I attach an event, for example click, on this element.

I tried the following, but with no luck: (no alert comes up)

document.getElementsByClassName('.keyword').onclick = function()
{
    alert(true);
    Search.addKey(this.getElementsByClassName('name')[0].innerHTML);
}

Requirements:

  • Without the onclick attribute
  • no jQuery or any other library

Note: the elements are not generated on page load. Their number can be different, each times you click a button for eg.

I need a way to attach to all tags with the class 'keyword' in the 'future'.

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

<div class="keyword"></div>

How can I attach an event, for example click, on this element.

I tried the following, but with no luck: (no alert comes up)

document.getElementsByClassName('.keyword').onclick = function()
{
    alert(true);
    Search.addKey(this.getElementsByClassName('name')[0].innerHTML);
}

Requirements:

  • Without the onclick attribute
  • no jQuery or any other library

Note: the elements are not generated on page load. Their number can be different, each times you click a button for eg.

I need a way to attach to all tags with the class 'keyword' in the 'future'.

Share Improve this question edited Jun 30, 2012 at 11:51 Novak asked Jun 30, 2012 at 11:38 NovakNovak 2,76810 gold badges46 silver badges64 bronze badges 3
  • tough, you'll have to do jquery's work. – user1086498 Commented Jun 30, 2012 at 11:39
  • For stuff like that jQuery or any other library is exactly what you should consider. Why reinvent the wheel? – ThiefMaster Commented Jun 30, 2012 at 12:38
  • 7 @ThiefMaster: Why reinvent the wheel? How about why load a large library to perform a fairly simple task? – user1106925 Commented Jun 30, 2012 at 12:42
Add a comment  | 

1 Answer 1

Reset to default 18

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)

  1. 暂无评论