How to get the class of the clicked element?

后端 未结 6 1854
抹茶落季
抹茶落季 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 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()

提交回复
热议问题