How to get the class of the clicked element?

后端 未结 6 1702
抹茶落季
抹茶落季 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:44
    $("div").click(function() {
      var txtClass = $(this).attr("class");
      console.log("Class Name : "+txtClass);
    });
    
    0 讨论(0)
  • 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+/);

    0 讨论(0)
  • 2020-11-29 16:57
    $("li").click(function(){
        alert($(this).attr("class"));
    });
    
    0 讨论(0)
  • 2020-11-29 16:57

    This should do the trick:

    ...
    select: function(event, ui){ 
       ui.tab.attr('class');
    } ,
    ...
    

    For more info about the ui.tab see http://jqueryui.com/demos/tabs/#Events

    0 讨论(0)
  • 2020-11-29 17:01

    I saw this question so I thought I might expand on it a little more. This is an expansion of the idea that @SteveFenton had. Instead of binding a click event to each li element, it would be more efficient to delegate the events from the ul down.

    For jQuery 1.7 and higher

    $("ul.tabs").on('click', 'li', function(e) {
       alert($(this).attr("class"));
    });
    

    Documentation: .on()

    For jQuery 1.4.2 - 1.7

    $("ul.tabs").delegate('li', 'click', function(e) {
       alert($(this).attr("class"));
    });
    

    Documentation: .delegate()

    As a last resort for jQuery 1.3 - 1.4

    $("ul.tabs").children('li').live('click', function(e) {
       alert($(this).attr("class"));
    });
    

    or

    $("ul.tabs > li").live('click', function(e) {
       alert($(this).attr("class"));
    });
    

    Documentation: .live()

    0 讨论(0)
  • 2020-11-29 17:11

    All the solutions provided force you to know the element you will click beforehand. If you want to get the class from any element clicked you can use:

    $(document).on('click', function(e) {
        clicked_id = e.target.id;
        clicked_class = $('#' + e.target.id).attr('class');
        // do stuff with ids and classes 
        })
    
    0 讨论(0)
提交回复
热议问题