How to save jquery selector for later use
I have the following code...
$('#item_' + code + ' .delete').hide();
$('#item_' + code + ' .deleting').show();
$('#item_' + code).slideUp(400, function() {
$(this).remove();
$('#top .message').html('Item has been deleted');
});
I want to save the selector I'm using in a variable and use it to perform operation instead of searching the DOM everytime.
So I save the selector like this...
var saved = $('#item_' + code);
But how do I change the rest of the code? I'm not very familiar 开发者_JAVA百科with jQuery, hence wondering how this can be done. Will this work...
$(saved).(' .delete').hide();
$(saved).(' .deleting').hide();
$(saved).slideUp(400, function() {
$(this).remove();
$('#top .message').html('Item has been deleted');
});
I'll add another alternative
$('.delete', saved).hide();
$('.deleting', saved).show()
...
You can use find()
:
var saved = $('#item_' + code);
saved.find('.delete, .deleting').hide();
saved.slideUp(400, function() {
$(this).remove();
$('#top .message').html('Item has been deleted');
});
You can store it in a variable:
var myVar = $('#item_' + code + ' .delete').hide();
and then if you want to add to it just add to the var:
myVar.css("background","green");
which is equivalent to:
$('#item_' + code + ' .delete').hide().css("background","green");
Use the find
or children
methods which allow you to apply selectors to the result of a previous query.
E.g.
var saved = $('#item_' + code);
saved.find(".delete").hide();
saved.find(".deleting").show();
saved.slideUp(400, function() {
$(this).remove();
$('#top .message').html('Item has been deleted');
});
Use the .each function on your saved selection
var SavedStuff = $(<something>);
// other code
SavedStuff.each( function (i, element) {
$(element).<jquery function>;
});
For example:
var SavedStuff = $(".Square"); // save all items with Square class
// Other code
// Later, add rhomboid to all squares
SavedStuff.each( function (i, element) {
$(element).addClass("Rhomboid");
});
Try this...
var saved = ('#item_' + code);
$(saved + ' .delete').hide();
$(saved + ' .deleting').show();
$(saved).slideUp(400, function() {
$(this).remove();
$('#top .message').html('Item has been deleted');
});
精彩评论