Programing

JQuery를 사용하여 이벤트를 발생시킨 요소의 클래스 가져 오기

lottogame 2020. 10. 31. 09:11
반응형

JQuery를 사용하여 이벤트를 발생시킨 요소의 클래스 가져 오기


어쨌든 클릭 이벤트가 시작될 때 클래스를 얻을 수 있습니까? 내 코드는 아래와 같이 id에서만 작동하지만 클래스에서는 작동하지 않습니다.

$(document).ready(function() {
  $("a").click(function(event) {
    alert(event.target.id + " and " + event.target.class);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>

<body>
  <a href="#" id="kana1" class="konbo">click me 1</a>
  <a href="#" id="kana2" class="kinta">click me 2</a>
</body>

</html>

여기에 jsfiddle 코드


시험:

$(document).ready(function() {
    $("a").click(function(event) {
       alert(event.target.id+" and "+$(event.target).attr('class'));
    });
});

여기에는 전체 클래스가 포함됩니다 (요소에 둘 이상의 클래스가있는 경우 공백으로 구분 된 여러 클래스 일 수 있음). 코드에는 "konbo"또는 "kinta"가 포함됩니다.

event.target.className

jQuery를 사용하여 이름으로 클래스를 확인할 수 있습니다.

$(event.target).hasClass('konbo');

addClassremoveClass를 사용하여 추가하거나 제거합니다 .


아래 배열의 모든 클래스를 얻을 수 있습니다.

event.target.classList

$(document).ready(function() {
  $("a").click(function(event) {
    var myClass = $(this).attr("class");
    var myId = $(this).attr('id');
    alert(myClass + " " + myId);
  });
})
<html>

<head>
  <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
</head>

<body>
  <a href="#" id="kana1" class="konbo">click me 1</a>
  <a href="#" id="kana2" class="kinta">click me 2</a>
</body>

</html>

이것은 나를 위해 작동합니다. jQuery에는 event.target.class 함수가 없습니다.


jQuery 1.7을 사용하는 경우 :

alert($(this).prop("class"));

또는:

alert($(event.target).prop("class"));

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!

참고URL : https://stackoverflow.com/questions/11026056/getting-the-class-of-the-element-that-fired-an-event-using-jquery

반응형