Getting the class of the element that fired an event using JQuery

后端 未结 6 1279
独厮守ぢ
独厮守ぢ 2021-01-30 08:04

is there anyway to get the class when click event is fired. My code as below, it only work for id but not class.

6条回答
  •  天涯浪人
    2021-01-30 08:45

    Careful as target might not work with all browsers, it works well with Chrome, but I reckon Firefox (or IE/Edge, can't remember) is a bit different and uses srcElement. I usually do something like

    var t = ev.srcElement || ev.target;
    

    thus leading to

    $(document).ready(function() {
        $("a").click(function(ev) {
            // get target depending on what API's in use
            var t = ev.srcElement || ev.target;
    
            alert(t.id+" and "+$(t).attr('class'));
        });
    });
    

    Thx for the nice answers!

提交回复
热议问题