I have some list elements with dynamically id changing. Next i give this id's to other element, as a class one by one. So, this is my code:
$('#rounded_items li').one({click: function(){
$('#back_button').addClass(this.id);
}});
and #back_button
receives classes 1, 2, 3, 4 from #rounded_items li
. How can i grab the last class from back_button
and give it to #rounded_items
by click.
Is there any possible to give back the last class from element who receives this class?
maybe you can store it as data
$('#rounded_items li').one('click', function(){
var classes = $('#back_button').attr('class').split(/\s+/);
var last = classes[classes.length-1];
$.data($('#back_button')[0],'lastclass',last);
$('#back_button').addClass(this.id);
});
$('#back_button').click(function(){
var lastclass = $.data($('#back_button')[0],'lastclass');
$('#rounded_items').addClass(lastclass);
var classes = $('#back_button').attr('class').split(/\s+/);
$.data($('#back_button')[0],'lastclass',classes[classes.length-3]);
$('#back_button').removeClass(classes[classes.length-1]);
});
you can also try this:
$('#back_button').click(function(){
var classes = $('#back_button').attr('class').split(/\s+/);
$('#rounded_items').addClass(classes[classes.length-2]);
$('#back_button').removeClass(classes[classes.length-1]);
});
Use an array to store the ids, not a class attribute!
var stack = [];
$('#rounded_items li').one('click',function(){
stack.push(this.id);
});
$('#back_button').click(function(){
$('#rounded_items').setClass(stack.pop());
});
I'm assuming that your classes aren't really being used to style anything, as they're not legal CSS identifiers. If the intent is just to store some state, use .data
:
var $back = $('#back_button');
$back.data('state', []); // empty array to store state
$('#rounded_items li').one({click: function() {
$back.data('state').push(this); // store clicked element
});
$back.on('click', function() {
var elem = $back.date('state').pop(); // retrieve last clicked element
if (elem) {
// do something with elem...
}
});
If the code is all in the same lexical scope you can just use a local array to store the state without using .data()
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.