Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...