使用onclick从元素中获取类名

car*_*mba 5 javascript jquery onclick

由于不同的原因,我不能使用$('.class').点击或打开('点击',函数..)

所以我真的必须使用html元素中的onclick =""事件.

有没有办法从onclick发生的元素中找出类?

和小提琴http://jsfiddle.net/Aw8Rb/

感谢您的帮助!

<!DOCTYPE html>
<html>
<head>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>

<span class="classic one"   onclick="someFunction('one')">CLICK HERE</span>
<span class="classic two"   onclick="someFunction('two')">CLICK HERE</span>
<span class="classic three" onclick="someFunction('three')">CLICK HERE</span>
<span class="classic four"  onclick="someFunction('four')">CLICK HERE</span>


<script type="text/javascript">

    function someFunction(abc) {
        alert(abc);
        alert($(this).attr('class'));

    }

</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

bip*_*pen 23

this调用函数时需要传递引用

试试这个

<span class="classic one"   onclick="someFunction(this,'one')">CLICK HERE</span>
......  //same for others
Run Code Online (Sandbox Code Playgroud)

jQuery的

function someFunction(obj,abc) {
        alert(abc);
        alert($(obj).attr('class'));

    }
Run Code Online (Sandbox Code Playgroud)

用普通的javascript(没有Jquery)

function someFunction(obj,abc) {
        alert(obj.className);
}
Run Code Online (Sandbox Code Playgroud)

在这里小提琴


小智 6

this.className 这里使用的非jquery方式.