Can you be able to contain variables that can be used in multiple functions in jQuery, example:
开发者_开发知识库var self = $(this);
var box = self.parents('.box');
$('#title').click(function()
{
self.css('background', 'red');
box.slideDown('slow');
}).dblclick(function()
{
self.css('background', 'green');
box.slideUp('slow');
});
So that self
and box
can be used within these event functions so I don't have to keep doing this:
$('#title').click(function()
{
var self = $(this);
var box = self.parents('.box');
self.css('background', 'red');
}).dblclick(function()
{
var self = $(this);
var box = self.parents('.box');
self.css('background', 'green');
});
But question is, is it possible, if so, how can you do that?
While the global variables can be accessed, they won't contain what you're after because this
is a special keyword that has a different value depending on where it is placed. In your example it's evaluated once, in the global scope, rather than in each function.
In short, the global variables that you've described are not a good idea. Instead, you can chain your code so that the self
variable need not be created at all:
$('#title').click(function()
{
$(this).css('background', 'red').parents('box').slideDown('slow');
}).dblclick(function()
{
$(this).css('background', 'green').parents('box').slideUp('slow');
});
You can't do what you are trying to do, but you could do something like this:
function getBoxes(selector) {
return $(selector).parents('.box');
}
$('#title').click(function()
{
getBoxes(this).css('background', 'red');
}).dblclick(function()
{
getBoxes(this).css('background', 'green');
});
You could, as @box9 mentions, just chain your calls together. That is what this does essentially. You could also change the function above to handle the color change for you, especially if that is the only thing you are using this for.
function colorBoxes(selector, color) {
$(selector).parents('.box').css('background', color);
}
$('#title').click(function()
{
colorBoxes(this, 'red');
}).dblclick(function()
{
colorBoxes(this, 'green');
});
It is possible:
var titleEl = $('#title');
var boxEl = titleEl.parents('.box');
titleEl.click(function()
{
titleEl.css('background', 'red');
boxEl.slideDown('slow');
}).dblclick(function()
{
titleEl.css('background', 'green');
boxEl.slideUp('slow');
});
although that's a bad idea IMO, because global variables are usually a bad idea, especially when they're being used because its easier.
More importantly, if your $('#title') wasn't an id, and therefore a single element, but maybe a class $('.title') and many elements, the code wouldnt work as it does now (because each reference to titleEl.css() would change ALL instances of the class). which shows that the global variable model is brittle.
it also doesnt lend itself to dynamically added DOM elements, because the assignment takes place only once.
精彩评论