jQuery 使用 event.target 获取类值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2128755/
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
use event.target to get the class value?
提问by ajsie
i have a DOM element with class='tag'.
我有一个带有 class='tag' 的 DOM 元素。
i want to check if the class value is tag and alert a message if it's true.
我想检查类值是否为 tag 并在为 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?
但它没有用。您可以使用 event.target.id 获取 id 而不是使用此代码的类?在 event.target 之后你可以拥有的所有值是什么?
回答by Avisek Chakraborty
if( $(event.target).hasClass("tag") )
{
alert("yes");
}
This will work fine.
这将正常工作。
回答by CMS
At first, the event
argument work only for event handlers, and you are using the $.each
method.
起初,该event
参数仅适用于事件处理程序,并且您正在使用该$.each
方法。
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.
我真的不认为您想要/需要使用该$.each
方法,因为您使用的是#id
选择器,并且 id 应该是唯一的。
To check if an element contains an specific class you can use the hasClass
method:
要检查元素是否包含特定类,您可以使用以下hasClass
方法:
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 wordin JavaScript, the same thing happens with other attributes like for
, should be accessed as htmlFor
...
此外,如果您有一个 DOM 元素,要获取它的 class 属性,您应该使用它className
来访问它,class
因为它class
是JavaScript 中未来的保留字,同样的事情发生在其他属性上,例如for
, 应该被访问为htmlFor
...
回答by tfwright
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:
您错误地使用了 jquery 的 each 方法。它需要两个参数,它们都不是事件(会响应目标属性)。从文档:
$.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.
有关检查元素是否具有给定类名的正确方法,请参阅 CMS 的答案。
回答by Justin Bull
Here you go.
干得好。
$("div").each(function (index, domEle) {
if (domEle.hasClass("tag")) {
console.log('yes');
} else {
console.log('no');
}
});
回答by Pedro Lopes
Just use inside the condition:
只需在条件内使用:
!domEle.hasClass("tag")