jQuery如何获取最后单击的元素的类或ID? [英] jQuery how to get the class or id of last clicked element?
问题描述
我正在尝试获取最后点击的元素的类或ID.这是我在此处 ...
I am trying to get the class or an id of the last clicked element. This is what I have based off of what I found here...
HTML
<a href="" class="button">Button</a>
JQUERY
$('.button').click(function () {
myFuntion();
});
function myFunction (e) {
e = e || event;
$.lastClicked = e.target || e.srcElement;
var lastClickedElement = $.lastClicked;
console.log(lastClickedElement);
}
这是我想要的,但是我不确定如何进行修改,这样我就可以得到课程.
This sort of does what I want, but I am not sure how to go about modifying it so I can get just the class.
我也尝试过使用此解决方案,但无法不能让它与我的代码一起使用.
I have also tried using this solution but couldn't get it to work with my code.
$('.button').click(function () {
myFuntion();
});
function myFunction(){
var lastID;
lastID = $(this).attr("id");
console.log(lastID);
}
执行此操作时,控制台日志会以未定义的形式返回.我可能缺少明显的东西.任何帮助深表感谢.谢谢.
When I do this my console log comes back as undefined. I am probably missing something obvious. Any help is much appreciated. Thanks.
推荐答案
您可以将clicked元素作为参数传递给函数:
You can pass clicked element as parameter to your function:
$('.button').click(function () {
myFunction(this);
});
function myFunction(element) {
console.log(element);
console.log(element.id);
console.log($(element).attr("class"));
}
更新添加了 jsfiddle
这篇关于jQuery如何获取最后单击的元素的类或ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!