get class name from element with onclick

后端 未结 7 1915
我在风中等你
我在风中等你 2020-12-10 08:01

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.

相关标签:
7条回答
  • 2020-12-10 08:21

    From jsfiddle you provided, edit your code like below and you'll get answer (class) properly.

    <span class="classic four"  onclick="someFunction(this,'four')">CLICK HERE</span>
    
    function someFunction(obj,abc) {
        alert(abc);
        alert(obj.getAttribute('class'));   
    }
    

    Pass this as first argument and then access it in function with obj. After that you can use obj.getAttribute('class')

    0 讨论(0)
  • 2020-12-10 08:21

    Add this as an argument to the inline event handler:

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

    Then use the className property of element to get the className

    function someFunction(e,abc) {
          console.log(this);
          alert(e.className);
    }
    

    Working Example http://jsfiddle.net/Aw8Rb/8/

    0 讨论(0)
  • 2020-12-10 08:22

    If you add the element to the argument you can use it into your function to retrieve all data that you want
    Try this:

        <span class="classic one"   onclick="someFunction('one',this)">CLICK HERE</span>
        <span class="classic two"   onclick="someFunction('two',this)">CLICK HERE</span>
        <span class="classic three" onclick="someFunction('three',this)">CLICK HERE</span>
        <span class="classic four"  onclick="someFunction('four',this)">CLICK HERE</span>
    
    
        <script type="text/javascript">
    
            function someFunction(abc,obj) {
                alert(abc);
                alert($(obj).attr('class'));
    
            }
        </script>
    

    DEMO

    0 讨论(0)
  • 2020-12-10 08:31

    A non-jquery way using this.className here.

    0 讨论(0)
  • 2020-12-10 08:32

    Pass this.className as the parameter .. eg.

    <input type="button" onclick="abc(this.className)" />
    
    0 讨论(0)
  • 2020-12-10 08:40

    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

    0 讨论(0)
提交回复
热议问题