JavaScript跟踪点击div排除内部ID?

时间:2013-12-21 18:37:53

标签: javascript

我有以下JavaScript代码来跟踪div的点击次数:

    var anchor = document.getElementById('clickMe');
    if (anchor.addEventListener) {
        anchor.addEventListener('click', clickHandlerOpen, false);
    } else if (anchor.attachEvent) {
        anchor.attachEvent('onclick', function () {
            return clickHandlerOpen.apply(anchor, [window.event])
        });
    }

我的HTML看起来像这样:

<div id="clickMe">
     <div id="someContent"><p>hello</p></div>
     <div id="closeMe">X</div>
</div>

如何从上面的点击处理程序中排除ID closeMe?我希望closeMe拥有自己的。

请注意,我不想使用jQuery

1 个答案:

答案 0 :(得分:4)

检查函数中单击元素的target.id

clickHandlerOpen(event) {
    //Satisfy IE8
    event = event || window.event; // get window.event if argument is falsy (in IE)

    // get srcElement if target is falsy (IE)
    var targetElement = event.target || event.srcElement;

    if (targetElement.id == 'closeMe') return false;
    //your code here
}