转换用于处理多个实例的脚本
Convert script for working with multiple instances
让我们看看这个脚本,它是一个简单的旋转
$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
我知道第一个选项应该是再次重写,但你们中有人看到能让它重复使用的快速解决方案吗?
一把小提琴:https://jsfiddle.net/6z8n5pnq/多重小提琴: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
组件的上下文。稍微修正了你的小提琴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);
});
},
}
相关文章:
- 当包含另一个asp文件时,是否也包含所有引用的样式和脚本页面
- 一个用户脚本的两个实例如何在帧之间进行通信
- Typescript模块和systemjs.从内联脚本实例化类
- 与内容脚本的所有实例交谈
- Javascript:在脚本后附加一个对象,并创建一个本地实例
- Wordpress jQuery 脚本不会在具有 jQuery.noConflict 用法的一个实例上启动
- 如何在脚本之外创建主干集合的实例
- 重复javascript的功能,脚本中没有相同代码的多个实例
- Mongo脚本在本地运行很快,但如果在远程实例上运行就很慢
- 如何在protractor的浏览器实例中手动注入脚本标记
- 通过(Java脚本)接口从shell脚本控制Java实例
- 如何获取"this"的当前实例?文件在谷歌应用程序脚本
- 从两个相等的脚本实例中删除冲突
- Java脚本引擎类实例化
- Google Apps脚本,用于发现Google工作表的两列之间的差异,忽略空白单元格和多个实例
- 从当前脚本(即thisscript.js?id=1&type=2)的url获取参数,不能与多个实例一起工作
- Java脚本:在两个不同的.js中使用相同的实例
- 转换用于处理多个实例的脚本
- jQuery:尝试动态加载jQuery.在脚本运行之后才进行实例化
- ASP.NET 客户端脚本连接到实例