jquery e.target.hasClass 不工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12155050/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:22:12  来源:igfitidea点击:

jquery e.target.hasClass not working

jqueryeventsonclickclassname

提问by user961627

I dynamically create a new div(with a "textbox" class and ID), and some other elements inside of it, and later on in my code I bind that divto the click event, and display the element clicked, like so:

我动态创建一个新的div(带有“文本框”类和 ID),以及其中的一些其他元素,稍后在我的代码中,我将其绑定div到 click 事件,并显示被点击的元素,如下所示:

$('#textbox_'+i).bind('click', function(event){
    alert(event.target.className);
}

This is fine, and it'll give me textboxas one of the classes displayed. But event.target.hasClass()doesn't seem to work. So, when I do the following, nothing happens:

这很好,它会给我textbox作为显示的类之一。但event.target.hasClass()似乎不起作用。因此,当我执行以下操作时,没有任何反应:

$('#textbox_'+i).bind('click', function(event){
    if(event.target.hasClass('textbox')) { alert('got it!'); }
}

I tried it a few different ways and it appears to me that event.target.hasClass()just doesn't work. Is there another way to deal with events or am I doing something wrong?

我尝试了几种不同的方法,但在我看来这event.target.hasClass()不起作用。有没有另一种处理事件的方法,或者我做错了什么?

回答by adeneo

You're trying to use a jQuery method, hasClass(), on a standard DOM element. You need to convert the plain JS DOM element e.targetto a jQuery object, like so:

您正尝试hasClass()在标准 DOM 元素上使用 jQuery 方法 , 。您需要将普通的 JS DOM 元素e.target转换为 jQuery 对象,如下所示:

$(event.target).hasClass('textbox')

And you end up with :

你最终得到:

$('#textbox_'+i).on('click', function(event){
     if( $(event.target).hasClass('textbox')) alert('got it!');
});

Notice the use of on(), the proper closing of the clickfunction, and you don't need curly brackets in your if statement if you're only executing a simple alert.

注意 的使用on()click函数的正确关闭,如果您只是执行一个简单的警报,则您的 if 语句中不需要大括号。

回答by iarroyo

If you want to keep using your JS DOM element plain without use jQuery:

如果你想继续使用你的 JS DOM 元素而不使用 jQuery:

event.target.classList.contains('textbox')