Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

javascript - get class name from element with onclick

Because of different reasons I can NOT use $('.class').click or on('click', function..)

So I really have to use the onclick="" event from the html element.

Is there a way to find out the class from the element where the onclick happens?

and the fiddle http://jsfiddle.net/Aw8Rb/

Thanks for all the help!

<!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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you need to pass this reference when calling the function

try this

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

jquery

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

    }

with plain javascript (without Jquery)

function someFunction(obj,abc) {
        alert(obj.className);
}

fiddle here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...