Hey all. Basically, I need "(this)" in my function to correspond to this selection:
$(".widget .portfolio img")
But I want alternative ways of running this function, one when it is cilcked, and one in intervals, like this:
function cycle()
{
var poo = $(this).attr("id"开发者_Go百科);
$(".poo").html(poo);
}
$(".widget .portfolio img").click(function() {
cycle();
});
setInterval(function() {
cycle();
}, 4000);
});
The problem is that when the interval runs, the function's value of "(this)" is that of the setInterval function - but I want it to be the selection I said above... if I could do something like this, it would be ideal:
setInterval(function() {
cycle($(".widget .portfolio img"));
...
I think I just need a simple something in the function... any ideas? Thanks in advance :)
You can use call()
or apply()
or using jQuery 1.4+ jQuery.proxy()
.
Using call()
/ apply()
(the only difference between these is passing arguments to the function). Every function can be called using call/apply, the first argument will be the context (this
) for the function call, and the second/more arguments are the arguments to the function. apply()
takes the function arguments as an array, where call()
takes them individually.
var $imgs = $('.widget .portfolio img'), imgNum = -1;
setInterval(function() {
imgNum = (imgNum + 1) % $imgs.length;
// to simulate cycling through the items for instance?
cycle.call($imgs.get(imgNum));
},4000);
jQuery.proxy()
This function is slightly different (and not really applicable to this situation), but can also be used to set the this
context for a function. What proxy()
does is take a function, and returns another function that calls the original function forcing its context to what you specify. Here's an example of using $.proxy()
to map a call to always be in the context of the calling object.
pass a reference (or a jquery selector) to cycle.
function cycle(obj)
{
var poo = obj.attr("id");
$(".poo").html(poo);
}
or
function cycle(sel)
{
var poo = $(sel).attr("id");
$(".poo").html(poo);
}
then you can use either cycle($(".widget .portfolio img"))
or cycle(".widget .portfolio img")
according to which you prefer.
My preference would be passing a reference, as I could then do this:
$(".widget .portfolio img").click(function() {
cycle($(this));
});
setInterval(function() {
cycle($(".widget .portfolio img"));
}, 4000);
function cycle(me)
{
var poo = me.attr("id");
$(".poo").html(poo);
};
$(".widget .portfolio img").click(function() {
cycle($(this));
});
setInterval('cycle($(".widget .portfolio img"))', 4000);
精彩评论