点击获取div的类名

时间:2014-11-14 09:40:13

标签: javascript html dom

我想获得div的类名。它适用于Chrome,但我在使用IE5时遇到问题。如果我单击div元素,则返回undefined

HTML:

<div class="wrapper" id="deneme">
    <div id="container">
        <input id="mytextboxid" class="mytextboxclass" type="textbox" />
        <input id="mybuttonid" class="mybuttonclass" type="button" value="tikla" />
        <div id="innerDivid" class="divElementClass">Div Element</div>
    </div>
</div>

JavaScript:

var x = document.getElementsByTagName("DIV");

for (var i=0; i<x.length; i++) {
    if (x[i].addEventListener) {
        x[i].addEventListener('click', redirect, false);
    } else if (x[i].attachEvent) {
        x[i].attachEvent('on' + 'click', redirect);
    }
}
function redirect() {
    alert(this.className);
}

解决方案是:

function redirect(e){
    var elem, evt = e ? e : event;
    if (evt.srcElement)  elem = evt.srcElement;
    else if (evt.target) elem = evt.target;
    alert(''
            + 'You clicked the following HTML element: \n <'
            + elem.getAttribute('className').toUpperCase()
            + '>'
    )
    return true;
}

感谢所有回复

1 个答案:

答案 0 :(得分:1)

function redirect(e) {
    e = e || window.event;

    var target = e.target || e.srcElement;
    // alert(target.className);  
    alert(target.getAttribute('class') || target.getAttribute('className'));
}

http://jsbin.com/nucofe/1/edit?html,js,output