How to get the class of the clicked element?

后端 未结 6 1807
抹茶落季
抹茶落季 2020-11-29 16:34

I can\'t figure it out how to get the class value of the clicked element.

When I use the code bellow, I get \"node-205\" every time

6条回答
  •  抹茶落季
    2020-11-29 16:45

    Here's a quick jQuery example that adds a click event to each "li" tag, and then retrieves the class attribute for the clicked element. Hope it helps.

    $("li").click(function() {
       var myClass = $(this).attr("class");
       alert(myClass);
    });
    

    Equally, you don't have to wrap the object in jQuery:

    $("li").click(function() {
       var myClass = this.className;
       alert(myClass);
    });
    

    And in newer browsers you can get the full list of class names:

    $("li").click(function() {
       var myClasses = this.classList;
       alert(myClasses.length + " " + myClasses[0]);
    });
    

    You can emulate classList in older browsers using myClass.split(/\s+/);

提交回复
热议问题