Javascript 使用 JQuery 获取触发事件的元素的类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11026056/
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
Getting the class of the element that fired an event using JQuery
提问by Redbox
is there anyway to get the class when click event is fired. My code as below, it only work for id but not class.
当点击事件被触发时,无论如何都可以获得类。我的代码如下,它只对 id 有效,对 class 无效。
$(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 code here
jsfiddle 代码在这里
回答by broesch
Try:
尝试:
$(document).ready(function() {
$("a").click(function(event) {
alert(event.target.id+" and "+$(event.target).attr('class'));
});
});
回答by Paul
This will contain the full class (which may be multiple space separated classes, if the element has more than one class). In your code it will contain either "konbo" or "kinta":
这将包含完整的类(如果元素有多个类,则可能是多个空格分隔的类)。在您的代码中,它将包含“konbo”或“kinta”:
event.target.className
You can use jQuery to check for classes by name:
您可以使用 jQuery 按名称检查类:
$(event.target).hasClass('konbo');
and to add or remove them with addClassand removeClass.
并使用addClass和removeClass添加或删除它们。
回答by Vishesh Mishra
You will get all the class in below array
您将获得以下数组中的所有类
event.target.classList
回答by drjay
$(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>
This works for me. There is no event.target.class function in jQuery.
这对我有用。jQuery 中没有 event.target.class 函数。
回答by Evan Mulawski
If you are using jQuery 1.7:
如果您使用的是 jQuery 1.7:
alert($(this).prop("class"));
or:
或者:
alert($(event.target).prop("class"));
回答by Rom
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
小心,因为target
可能不适用于所有浏览器,它适用于 Chrome,但我认为 Firefox(或 IE/Edge,不记得了)有点不同,它使用 srcElement。我通常做类似的事情
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!
谢谢你的好答案!