javascript jQuery 如何获取上次单击元素的类或 id?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12181770/
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
jQuery how to get the class or id of last clicked element?
提问by Kris Hollenbeck
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...
我正在尝试获取最后一次单击元素的类或 ID。这是我根据我在此处找到的内容...
HTML
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 thissolution 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.
当我这样做时,我的控制台日志返回未定义。我可能遗漏了一些明显的东西。任何帮助深表感谢。谢谢。
采纳答案by Zbigniew
回答by Explosion Pills
A couple of ways come to mind:
想到了几种方法:
$(".button").click(myFunction);
Should work with the above myFunction
.
应该和上面的一起工作myFunction
。
$(".button").click(function () { myFunction($(this)); });
function myFunction($elem) {
var lastID;
lastID = $elem.attr('id');
$.data('lastID', lastID);
}
回答by David says reinstate Monica
In order to get the class-name of the element, assuming you have an accurate reference to the element from which you want to retrieve the data:
为了获取元素的类名,假设您对要从中检索数据的元素有准确的引用:
var lastClickedElement = $.lastClicked,
lastClickedElementClassNames = lastClickedElement.className;
This does return the full list of all the classes of the element though.
不过,这确实返回了元素所有类的完整列表。
回答by Dan Barzilay
$('.button').click(function () {
myFuntion(this);
});
function myFunction(ele){
var lastID;
lastID = $(ele).attr("id");
console.log(lastID);
}
回答by Burimi
First Select all possible DOM Elements
首先选择所有可能的 DOM 元素
var lastSelectedElement = null
$(document).ready(function(){
$("*").live("click",function(){
lastSelectedElement = $(this);
myFunction($(this));
});
});
function myFunction(element) {
console.log(element);
console.log(element.id);
console.log($(element).attr("class"));
}
than you could play with lastSelectedElement
by grabbing it's ID or Class with jQuery .attr("ID OR CLASS");
比你可以lastSelectedElement
通过使用 jQuery 获取它的 ID 或类来玩.attr("ID OR CLASS");