获取最后点击的ID – jQuery

我有三个div …

当我点击一个随机div时,它将div的顺序移到顶部(例如,让我们使用ID#2)。 因此,在此之后,div可能会按时间顺序排列。 以下示例……

 

所以,如果是这种情况,有没有办法获得我点击的最后一个div ID?

你是说这个吗?

 var lastID; // document.ready $(function() { $("div").on("click", function() { lastID = $(this).attr("id"); }); }); function something() { // lastID is the id of the last div clicked. } 

在document.ready函数之外声明lastID意味着它可以全局访问,因此您可以在以后的其他函数中使用它。

您单击的最后一个将位于顶部,因此请使用:first selector:

 var lastId = $('div:first').attr('id'); 
 var lastClicked; $("div").on("click", function() { console.log(lastClicked); //last one console.log(this.id); //this one lastClicked = this.id; //makes this the last one }); 
 lastId = $("div#parent div:first").attr('id'); 
 var lastOne=""; $(function({ $('div').on("click",function(){ console.log(lastOne+"div was clicked before"); lastOne=$(this).attr('id');// id of the clicked div }); })); 

也许这对你有帮助!

创建名为LastId的var,将此var设置在click函数之外。 在click函数内部用它的id更新它。 所以喜欢

 $(document).ready(function(){ var LastId = ""; $('div').on("click",function() { LastId = $(this).attr('id'); }); }); 

希望这会有所帮助:D

我实际上经常使用类,如:

HTML:

 

jQuery的:

 $(".orderable").on("click", "div", function() { $(".orderable .lastClicked").removeClass("lastClicked"); $(this).addClass("lastClicked").prependTo(".orderable"); }); 

因此,当事情四处移动时,我确定了最后一个元素:

点击div:

 

正如其他人所提到的那样,在你的例子中,最后一次点击可能永远是列表中的第一个,在这种情况下你可以去:

jQuery的:

 $(".orderable div:first") // Probable selector for last clicked