让我们看看这个脚本,它是一个简单的轮播
$script = {
init: function(){
this.heros(3000);
},
heros: function (time) {
var t;
var $hero = $('.hero');
var $images = $('.hero > div');
$hero.data('current', 0);
var $bullets = $('<div>').addClass('bullets');
for ( var i = 0; i<$images.length; i++ ) {
var $item = $('<span>');
$item.on('click', function () {
clearTimeout(t);
play( $(this).index() );
});
if(i==0) { $item.addClass('active') }
$bullets.append( $item );
}
var play = function (current) {
if(current==undefined) {
current = $hero.data('current');
}
var nextMargin;
if ( (current+1) == $images.length ) {
nextMargin = 0 ;
$hero.data('current',0);
} else {
nextMargin = (current + 1 )*100;
$hero.data('current', (current + 1));
}
$images.eq(0).css('marginLeft', -nextMargin + '%');
$bullets.find('span').eq($hero.data('current')).addClass('active').siblings().removeClass('active');
clearTimeout(t);
t = setTimeout(play, time);
}
$hero.append($bullets);
t = setTimeout(play, time);
},
}
问题是,它效果很好,但前提是只有一个 .hero
元素。如果有多个项目符号混合在一起,并且它不尊重 .length
我知道选项一应该再次重写,但是你们中有人看到一个可以使其可重用的快速修复吗?
一个 fiddle :https://jsfiddle.net/6z8n5pnq/ 多 fiddle :https://jsfiddle.net/6z8n5pnq/1/
-编辑-
我尝试过:
定义先前的函数,在 init 上调用
preheros: function(time) {
var self = this;
$('.heros').each(function(){
self.heros($(this), time);
});
},
并编辑英雄的开始:
heros: function ($hero, time) {
var t;
/*var $hero = $('.hero');*/
var $images = $hero.find('>div');
但没有成功...
有什么想法吗?
-编辑-
天哪,是 $('.hero').each
而不是 $('.heros').each
它正在工作!
最佳答案
最简单的方法是使用 $(selector).each
函数隔离每个 .hero
组件的上下文。稍微纠正了你的 fiddle https://jsfiddle.net/6z8n5pnq/2/
function apply($hero, time){
var t;
var $images = $hero.children('div');
//all your logic here...
}
$script = {
init: function () {
this.heros(3000);
},
heros: function (time) {
$('.hero').each(function(){
apply($(this), time);
});
},
}
关于javascript - 转换脚本以处理多个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31188807/