jQuery Cycle Plugin For Loop
I have been stumped trying to figure out how to integrate a simple for loop to work with the jQuery Cycle plugin. In my basic example I am trying to create 15 cycle functions using jquery .hover()
and .cycle()
.
for(i=1;i<15;i++){
$(".t"+ i).hover(function() {
$('.projectTitle').cycle(i);
});
}
If I create 15 separate functions(per below) the script runs fine but I am in need of simplifying my code.
$('.t1').hover(function() {
开发者_JAVA百科 $('.projectTitle').cycle(1);
});
$('.t2').hover(function() {
$('.projectTitle').cycle(2);
});
$('.t3').hover(function() {
$('.projectTitle').cycle(3);
});
$('.t4').hover(function() {
$('.projectTitle').cycle(4);
});
...
Any help would be greatly appreciated.
You can circumvent the whole closure issue by storing i
as a data attribute in the DOM element itself:
for (var i=1; i<=15; i++) {
$('.t'+i).data("inc",i).hover(function() {
$('.projectTitle').cycle( $(this).data("inc") );
});
}
(Incidentally, you should probably replace all those classes with IDs, for performance.)
The "right" way to do this is with a JavaScript closure, which I'm no expert in, but I think should look like this:
for (var i=1; i<=15; i++) {
$('.t'+i).hover(
(function() {
var a = i;
return function() { $('.projectTitle').cycle( a ); }
})()
);
}
If they are in the correct order in the DOM you can use the index provided by jQuery's each and give them all the same class:
$('.t').each(function(index) {
$(this).mouseover( function() { // Use mouseover instead of hover, otherwise your function will be run on mouseover AND mouseout
$('.projectTitle').cycle( index );
}
});
精彩评论