use event.target to get the class value?

2020-06-03 05:25发布

i have a DOM element with class='tag'.

i want to check if the class value is tag and alert a message if it's true.

i wrote:

    $("#thread").each(function(event) {
        if(event.target.class == 'tag') alert('yes');
    });

but it didn't work. you can get the id with event.target.id but not the class with this code? what are all the values you can have after event.target?

标签: jquery
5条回答
做自己的国王
2楼-- · 2020-06-03 05:34
if( $(event.target).hasClass("tag") )
{
   alert("yes");
}

This will work fine.

查看更多
女痞
3楼-- · 2020-06-03 05:34

Just use inside the condition:

!domEle.hasClass("tag")
查看更多
叼着烟拽天下
4楼-- · 2020-06-03 05:36

Here you go.

$("div").each(function (index, domEle) {
    if (domEle.hasClass("tag")) {
        console.log('yes');
    } else {
        console.log('no');
    }
});
查看更多
在下西门庆
5楼-- · 2020-06-03 05:37

At first, the event argument work only for event handlers, and you are using the $.each method.

I don't really think that you want/need to use the $.each method, since you are using an #id selector, and id's should be unique.

To check if an element contains an specific class you can use the hasClass method:

if ($("#thread").hasClass('tag')) {
  //...
}

Also if you have a DOM element, to get it's class attribute, you should access it with className instead class, that's because class is a future reserved word in JavaScript, the same thing happens with other attributes like for, should be accessed as htmlFor...

查看更多
够拽才男人
6楼-- · 2020-06-03 05:44

you are using jquery's each method incorrectly. it takes two arguments, neither one of them is an event (that would respond to the target property). from the docs:

$.each([52, 97], function(index, value) { 
  alert(index + ': ' + value); 
});

See CMS's answer for the proper way of checking if elements have a given class name.

查看更多
登录 后发表回答